From 453fb636878fdf898a562adfcef69d0de21f0030 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 3 Oct 2026 11:27:49 +0000 Subject: [PATCH 01/18] feat(data): delete sequences into the archive's trash and restore them SequenceTrash plans (files, bytes, trash folder, blocked reasons) and moves each sequence folder whole into .titano/trash/ under its leases, next to a record of its index row and renders, then drops the index rows; restore moves it back (to a free folder when the old one is taken) and indexes it again from its sidecar with the same ids. The server's DELETE /sequences/{id} now uses it and refuses a sequence a job is working on (409 sequence_busy). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Archive.resx | 1 + i18n/en/Server.resx | 1 + i18n/it/Archive.it.resx | 1 + i18n/it/Server.it.resx | 1 + src/Titano.Data/Archiving/ArchiveService.cs | 24 +- src/Titano.Data/Archiving/SequenceTrash.cs | 381 ++++++++++++++++++ src/Titano.Server/Api/SequenceEndpoints.cs | 41 +- .../Archiving/ArchiveFixture.cs | 5 +- .../Archiving/SequenceTrashTests.cs | 241 +++++++++++ .../Titano.Server.Tests/Api/SequenceTests.cs | 24 ++ 10 files changed, 700 insertions(+), 20 deletions(-) create mode 100644 src/Titano.Data/Archiving/SequenceTrash.cs create mode 100644 tests/Titano.Data.Tests/Archiving/SequenceTrashTests.cs diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx index 2148b764..2b9444d0 100644 --- a/i18n/en/Archive.resx +++ b/i18n/en/Archive.resx @@ -48,6 +48,7 @@ Another Titano ({0}) is writing here. Try again shortly.long: error sentence The copy of {0} does not match the original.long: error sentence {0} could not be added to the sequence.long: error sentence + {0} is already in the library.long: error sentence {0} was written by a newer Titano (format {1}).long: error sentence The archive {0} is offline.long: error sentence The archive {0} is read-only.long: error sentence diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index 3d9acadf..708db05e 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -66,6 +66,7 @@ Too many attempts; wait a minute and try again.long Choose a password different from the current one.long You cannot do this to your own account.long + A job is working on this sequence, or it cannot move to the trash; try again when it is free.long The session expired; sign in again.long An environment variable sets this; change it there.long The sequence changed on the server; reload it and apply your edit again.long diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx index fd159c3b..d219e873 100644 --- a/i18n/it/Archive.it.resx +++ b/i18n/it/Archive.it.resx @@ -44,6 +44,7 @@ Un altro Titano ({0}) sta scrivendo qui. Riprova tra poco. La copia di {0} non corrisponde all'originale. Impossibile aggiungere {0} alla sequenza. + {0} è già nella libreria. {0} è stato scritto da un Titano più recente (formato {1}). L'archivio {0} non è raggiungibile. L'archivio {0} è di sola lettura. diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index ab68efee..27661ba8 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -64,6 +64,7 @@ Troppi tentativi; attendi un minuto e riprova. Scegli una password diversa da quella attuale. Non puoi farlo sul tuo account. + Un job sta lavorando su questa sequenza, oppure non può andare nel cestino; riprova quando è libera. La sessione è scaduta; accedi di nuovo. È impostato da una variabile d'ambiente; modificala lì. La sequenza è cambiata sul server; ricaricala e riapplica la modifica. diff --git a/src/Titano.Data/Archiving/ArchiveService.cs b/src/Titano.Data/Archiving/ArchiveService.cs index 24c8a4d9..f474a4ca 100644 --- a/src/Titano.Data/Archiving/ArchiveService.cs +++ b/src/Titano.Data/Archiving/ArchiveService.cs @@ -10,7 +10,8 @@ namespace Titano.Data.Archiving; /// /// What the desktop client and the server call to work with archives (BRIEF §7, §12.4, §12.5, §14.4): open, create -/// or adopt an archive, plan and apply mass renames, plan imports and card erases, query duplicates and orphans, and +/// or adopt an archive, plan and apply mass renames, plan imports and card erases, delete sequences into the trash and +/// restore them, query duplicates and orphans, and /// the job handlers for the long operations (enqueue them with ). /// public sealed class ArchiveService : IJobHandlerProvider @@ -29,6 +30,7 @@ public sealed class ArchiveService : IJobHandlerProvider Renamer = new MassRenamer(db, _writer, Indexer); Images = new ArchiveImages(db, _writer, Indexer); Imports = new ImportService(db, Ingest); + Trash = new SequenceTrash(db, _writer, Indexer); } public ArchiveIndexer Indexer { get; } @@ -42,6 +44,9 @@ public sealed class ArchiveService : IJobHandlerProvider public ArchiveImages Images { get; } public ImportService Imports { get; } + /// Deletes sequences into the archive's trash and restores them. + public SequenceTrash Trash { get; } + /// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs; register them on the . public IReadOnlyList CreateJobHandlers() => [ @@ -160,6 +165,23 @@ public sealed class ArchiveService : IJobHandlerProvider await Renamer.ApplyAsync(await LoadArchiveAsync(plan.ArchiveId, cancellationToken).ConfigureAwait(false), plan, progress, cancellationToken) .ConfigureAwait(false); + /// Dry run of moving sequences to their archive's trash. + public Task PlanDeleteAsync(IReadOnlyList sequenceIds, CancellationToken cancellationToken = default) => + Trash.PlanAsync(sequenceIds, cancellationToken); + + /// Moves exactly the planned sequences to the trash; returns the trash entries made. + public Task> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress? progress = null, + CancellationToken cancellationToken = default) => + Trash.DeleteAsync(plan, deletedBy, progress, cancellationToken); + + /// The sequences in an archive's trash, newest first. + public async Task> ListTrashAsync(Guid archiveId, CancellationToken cancellationToken = default) => + await Trash.ListAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); + + /// Moves a sequence back from the trash and indexes it again; null when its folder has no sidecar (a scan adopts it). + public async Task RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default) => + await Trash.RestoreAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), entryName, cancellationToken).ConfigureAwait(false); + /// Plans a card or folder import into an archive (nothing is copied). public async Task PlanImportAsync(Guid archiveId, string sourceRoot, ImportOptions options, Guid? cardId = null, IProgress? progress = null, CancellationToken cancellationToken = default) => diff --git a/src/Titano.Data/Archiving/SequenceTrash.cs b/src/Titano.Data/Archiving/SequenceTrash.cs new file mode 100644 index 00000000..5286fda4 --- /dev/null +++ b/src/Titano.Data/Archiving/SequenceTrash.cs @@ -0,0 +1,381 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Titano.Core.Archiving; +using Titano.Core.Diagnostics; +using Titano.Core.IO; +using Titano.Core.Localization; +using Titano.Core.Model; + +namespace Titano.Data.Archiving; + +/// Why a sequence cannot go to the trash; nothing of it is touched. +public enum DeleteBlock +{ + /// The archive is offline or read-only. + Offline, + + /// The photos lie in the archive root itself (a folder adopted in place): the root never moves. + ArchiveRoot, + + /// Other sequences live in folders below this one; moving it would take them along. + ContainsSequences, + + /// A job is running on the sequence, or paused in the middle of it. + Busy, + + /// The folder's sidecar names another sequence: the index is out of date (a scan fixes it). + ForeignSidecar, +} + +/// One sequence of a delete plan: its folder moves to and its index rows go. +/// Archive-relative folder the sequence folder moves to; null when it has no folder on disk (only its rows go). +/// Files under the folder (originals, proxies, exports, sidecars). +/// Their size on disk. +public sealed record DeleteStep(Sequence Sequence, string? TrashFolder, int Files, long Bytes); + +public sealed record BlockedDelete(Sequence Sequence, DeleteBlock Reason); + +/// The dry run of moving sequences to their archive's trash (BRIEF §0.2 rule 8): what moves, and what cannot. +public sealed record DeletePlan(IReadOnlyList Steps, IReadOnlyList Blocked) +{ + public int Frames => Steps.Sum(s => s.Sequence.FrameCount); + public int Files => Steps.Sum(s => s.Files); + public long Bytes => Steps.Sum(s => s.Bytes); + public int Renders => Steps.Sum(s => s.Sequence.RenderedCount); +} + +/// A deleted sequence kept in an archive's trash, as lists it. +/// Folder name inside the trash; pass it to . +/// Archive-relative folder the sequence came from (and returns to when it is free). +public sealed record TrashEntry(Guid ArchiveId, string Name, Guid SequenceId, string Title, string Folder, int Frames, int Files, long Bytes, + DateTimeOffset DeletedAt, string? DeletedBy); + +/// The plan no longer matches the index or the jobs (a sequence moved, vanished or got busy since it was made); nothing was deleted. +public sealed class StaleDeletePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan")) +{ + public Guid SequenceId { get; } = sequenceId; +} + +/// +/// Deleting sequences without erasing anything (BRIEF §0.2 rule 8, §12.2, §12.5): is the dry +/// run; moves each sequence folder whole — originals, proxies, exports and its sidecars — into +/// .titano/trash/<id> of its archive under the sequence's leases, next to a record of its index row and +/// renders, then removes the index rows. moves a folder back and indexes it again from its +/// sidecar with the same ids. The trash is a hidden folder of the archive, so scans never index it. +/// +public sealed class SequenceTrash +{ + /// Folder of the trash inside the archive's .titano. + public const string FolderName = "trash"; + + private const string RecordExtension = ".json"; + private const int JobPage = 200; + + private readonly TitanoDatabase _db; + private readonly SequenceWriter _writer; + private readonly ArchiveIndexer _indexer; + + /// A trash of its own (hosts without an ); lease files keep it in step with other writers. + public SequenceTrash(TitanoDatabase db, ArchiveServiceOptions? options = null) + : this(db, new SequenceWriter(options ?? new ArchiveServiceOptions()), null) + { + } + + internal SequenceTrash(TitanoDatabase db, SequenceWriter writer, ArchiveIndexer? indexer) + { + _db = db; + _writer = writer; + _indexer = indexer ?? new ArchiveIndexer(db, writer); + } + + /// The trash folder of an archive. + public static string TrashDirectory(ArchivePaths archive) => Path.Combine(archive.MetaDirectory, FolderName); + + /// The dry run: for each sequence, where its folder goes and how many files and bytes it holds, or why it cannot go. + /// A sequence is not in the index. + public async Task PlanAsync(IReadOnlyList sequenceIds, CancellationToken cancellationToken = default) + { + var busy = await BusySequencesAsync(cancellationToken).ConfigureAwait(false); + var archives = new Dictionary Locations)>(); + var steps = new List(); + var blocked = new List(); + var claimed = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var id in sequenceIds.Distinct()) + { + cancellationToken.ThrowIfCancellationRequested(); + var sequence = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) + ?? throw new ArgumentException($"Unknown sequence {id}.", nameof(sequenceIds)); + if (!archives.TryGetValue(sequence.ArchiveId, out var context)) + { + var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false) + ?? throw new ArgumentException($"Unknown archive {sequence.ArchiveId}.", nameof(sequenceIds)); + var paths = new ArchivePaths(archive.RootPath); + context = (archive, paths, ArchiveVolume.Probe(paths) == ArchiveAvailability.Online, + await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)); + archives[sequence.ArchiveId] = context; + } + if (Block(sequence, context.Paths, context.Online, context.Locations, busy) is { } reason) + { + blocked.Add(new BlockedDelete(sequence, reason)); + continue; + } + var folder = sequence.Folder.Length == 0 ? null : context.Paths.Sequence(sequence.Folder).Folder; + if (folder is null || !Directory.Exists(folder)) + { + steps.Add(new DeleteStep(sequence, null, 0, 0)); + continue; + } + var (files, bytes) = await Task.Run(() => Measure(folder, cancellationToken), cancellationToken).ConfigureAwait(false); + var name = EntryName(context.Paths, sequence.Id, claimed); + claimed.Add(name); + steps.Add(new DeleteStep(sequence, context.Paths.ToRelative(Path.Combine(TrashDirectory(context.Paths), name)), files, bytes)); + } + return new DeletePlan(steps, blocked); + } + + /// + /// Moves the planned sequences to the trash, one at a time, each completely (folder, then index rows) before the + /// next; cancelling stops between two sequences. Returns the trash entries made. + /// + /// Who asked (user name or client), kept in the trash record. + /// A sequence moved, vanished or got busy since the plan; nothing was deleted. + /// An archive went offline; sequences before it are in the trash. + public async Task> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress? progress = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(plan); + // A plan made before another change is refused before anything moves. + var fresh = await PlanAsync([.. plan.Steps.Select(s => s.Sequence.Id)], cancellationToken).ConfigureAwait(false); + if (fresh.Blocked is [var block, ..]) throw new StaleDeletePlanException(block.Sequence.Id); + foreach (var step in plan.Steps) + { + if (fresh.Steps.First(s => s.Sequence.Id == step.Sequence.Id).Sequence.Folder != step.Sequence.Folder) + throw new StaleDeletePlanException(step.Sequence.Id); + } + + var entries = new List(plan.Steps.Count); + for (var i = 0; i < fresh.Steps.Count; i++) + { + cancellationToken.ThrowIfCancellationRequested(); + if (await DeleteOneAsync(fresh.Steps[i], deletedBy, cancellationToken).ConfigureAwait(false) is { } entry) entries.Add(entry); + progress?.Report(i + 1); + } + return entries; + } + + /// The sequences in an archive's trash, newest first; records whose folder is gone are left out. + public async Task> ListAsync(Archive archive, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(archive); + var trash = TrashDirectory(new ArchivePaths(archive.RootPath)); + return await Task.Run(() => + { + if (!Directory.Exists(trash)) return (IReadOnlyList)[]; + var entries = new List(); + foreach (var path in Directory.EnumerateFiles(trash, "*" + RecordExtension)) + { + cancellationToken.ThrowIfCancellationRequested(); + var name = Path.GetFileNameWithoutExtension(path); + 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(); + }, cancellationToken).ConfigureAwait(false); + } + + /// + /// Moves a sequence back from the trash into its folder (or, when that is taken, a free one next to it) and indexes + /// it again from its sidecar with its ids, settings and renders. Returns the restored row; null when the folder has + /// no sidecar (the next scan adopts it). + /// + /// The index already holds that sequence. + /// The entry is not in the trash. + public async Task RestoreAsync(Archive archive, string name, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(archive); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + var paths = new ArchivePaths(archive.RootPath); + ArchiveVolume.EnsureWritable(paths); + var trash = TrashDirectory(paths); + var source = Path.Combine(trash, Path.GetFileName(name)); + var recordPath = source + RecordExtension; + if (!Directory.Exists(source) || ReadRecord(recordPath) is not { } record) + throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}."); + var id = record.Sequence.Id; + if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not null) + throw new InvalidOperationException(Loc.L("Archive.Error.InLibrary", record.Sequence.DisplayTitle)); + + var locations = (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Folder) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + var folder = FreeFolder(paths, record.Sequence.Folder, locations); + var sequence = paths.Sequence(folder); + await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false)) + { + Directory.CreateDirectory(Path.GetDirectoryName(sequence.Folder)!); + Directory.Move(source, sequence.Folder); + Log.Info("archive", $"{record.Sequence.DisplayTitle} restored from the trash to {folder}"); + if (!File.Exists(sequence.ManifestPath)) + { + File.Delete(recordPath); + return null; + } + var manifest = SequenceWriter.ReadLocked(sequence, id); + var kept = record.Sequence with { ArchiveId = archive.Id, Folder = folder, RenderedCount = 0 }; + 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(id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false); + foreach (var key in manifest.SessionKeys) await tx.Sequences.MapSessionKeyAsync(archive.Id, key, id, cancellationToken).ConfigureAwait(false); + foreach (var render in record.Renders) + await tx.Renders.InsertAsync(render with { OutputPath = Rebase(render.OutputPath, record.Sequence.Folder, folder) }, cancellationToken).ConfigureAwait(false); + await tx.CommitAsync(cancellationToken).ConfigureAwait(false); + } + await _indexer.RecordStampsAsync(archive, sequence, id, cancellationToken).ConfigureAwait(false); + File.Delete(recordPath); + } + return await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false); + } + + private async Task DeleteOneAsync(DeleteStep step, string? deletedBy, CancellationToken cancellationToken) + { + var sequence = step.Sequence; + var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false) + ?? throw new StaleDeletePlanException(sequence.Id); + var paths = new ArchivePaths(archive.RootPath); + ArchiveVolume.EnsureWritable(paths); + TrashEntry? entry = null; + await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false)) + using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait, + _writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false)) + { + var row = await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false); + if (row is null || row.Folder != sequence.Folder) throw new StaleDeletePlanException(sequence.Id); + if (step.TrashFolder is not null && sequence.Folder.Length > 0 && Directory.Exists(paths.Sequence(sequence.Folder).Folder)) + { + var folder = paths.Sequence(sequence.Folder); + if (File.Exists(folder.ManifestPath) && ManifestStore.ReadSequence(folder.ManifestPath).Id != sequence.Id) + throw new StaleDeletePlanException(sequence.Id); + var trash = TrashDirectory(paths); + Directory.CreateDirectory(trash); + var name = EntryName(paths, sequence.Id, new HashSet()); + var record = new TrashRecord(row, await _db.Renders.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false), step.Files, + step.Bytes, DateTimeOffset.UtcNow, deletedBy); + // The record first: a crash before the move leaves a record without a folder, which the listing ignores. + AtomicFile.WriteAllText(Path.Combine(trash, name + RecordExtension), JsonSerializer.Serialize(record, TrashJson.Default.TrashRecord)); + Directory.Move(folder.Folder, Path.Combine(trash, name)); + entry = Entry(archive.Id, name, record); + } + await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false)) + { + await tx.Sequences.DeleteAsync(sequence.Id, cancellationToken).ConfigureAwait(false); + await tx.Archives.DeleteFolderStateAsync(archive.Id, sequence.Folder, cancellationToken).ConfigureAwait(false); + await tx.CommitAsync(cancellationToken).ConfigureAwait(false); + } + } + Log.Info("archive", entry is null + ? $"{sequence.DisplayTitle} removed from the index (no folder on disk)" + : $"{sequence.DisplayTitle} moved to the trash: {sequence.Folder} → {entry.Name} ({step.Files} files, {step.Bytes} bytes)"); + return entry; + } + + private static DeleteBlock? Block(Sequence sequence, ArchivePaths paths, bool online, IReadOnlyList locations, + IReadOnlySet busy) + { + if (!online) return DeleteBlock.Offline; + if (busy.Contains(sequence.Id)) return DeleteBlock.Busy; + // An empty folder is the archive root of a folder adopted in place, or a server sequence still waiting for its first frame. + if (sequence.Folder.Length == 0) return sequence.FrameCount > 0 ? DeleteBlock.ArchiveRoot : null; + var prefix = sequence.Folder + "/"; + if (locations.Any(l => l.Id != sequence.Id && l.Folder.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) return DeleteBlock.ContainsSequences; + var sidecar = paths.Sequence(sequence.Folder).ManifestPath; + try + { + if (File.Exists(sidecar) && ManifestStore.ReadSequence(sidecar).Id != sequence.Id) return DeleteBlock.ForeignSidecar; + } + catch (InvalidDataException) + { + return DeleteBlock.ForeignSidecar; + } + return null; + } + + /// Sequences a running or paused job works on (an import, a render, a transfer, a proxy pass). + private async Task> BusySequencesAsync(CancellationToken cancellationToken) + { + var busy = new HashSet(); + foreach (var state in new[] { JobState.Running, JobState.Paused }) + { + string? cursor = null; + do + { + var page = await _db.Jobs.ListAsync(state, JobPage, cursor, cancellationToken).ConfigureAwait(false); + foreach (var job in page.Items) busy.UnionWith(job.TargetIds); + cursor = page.NextCursor; + } + while (cursor is not null); + } + return busy; + } + + private static (int Files, long Bytes) Measure(string folder, CancellationToken cancellationToken) + { + int files = 0; + long bytes = 0; + foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = 0 })) + { + cancellationToken.ThrowIfCancellationRequested(); + files++; + bytes += file.Length; + } + return (files, bytes); + } + + /// The sequence id, or the id with a time stamp when an earlier deletion of the same sequence is still in the trash. + private static string EntryName(ArchivePaths paths, Guid sequenceId, IReadOnlySet claimed) + { + var trash = TrashDirectory(paths); + var name = sequenceId.ToString("N"); + var stamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture); + for (var n = 1; claimed.Contains(name) || Directory.Exists(Path.Combine(trash, name)); n++) + name = $"{sequenceId:N}-{stamp}" + (n > 1 ? "-" + n.ToString(System.Globalization.CultureInfo.InvariantCulture) : string.Empty); + return name; + } + + /// The original folder when it is free on disk and in the index, else "folder (2)", "folder (3)", … + private static string FreeFolder(ArchivePaths paths, string folder, IReadOnlySet indexed) + { + var candidate = folder; + for (var n = 2; indexed.Contains(candidate) || Directory.Exists(paths.Sequence(candidate).Folder); n++) + candidate = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{folder} ({n})"); + return candidate; + } + + /// A render stored inside the old folder points into the folder it was restored to. + private static string Rebase(string outputPath, string from, string to) => + from != to && outputPath.StartsWith(from + "/", StringComparison.Ordinal) ? to + outputPath[from.Length..] : outputPath; + + private static TrashEntry Entry(Guid archiveId, string name, TrashRecord record) => + new(archiveId, name, record.Sequence.Id, record.Sequence.DisplayTitle, record.Sequence.Folder, record.Sequence.FrameCount, record.Files, + record.Bytes, record.DeletedAt, record.DeletedBy); + + private static TrashRecord? ReadRecord(string path) + { + try + { + return JsonSerializer.Deserialize(File.ReadAllText(path), TrashJson.Default.TrashRecord); + } + catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) + { + Log.Warning("archive", $"Trash record {path} is unreadable", ex); + return null; + } + } +} + +/// What the trash keeps next to a deleted folder: the index row and renders the sidecar does not carry. +internal sealed record TrashRecord(Sequence Sequence, IReadOnlyList Renders, int Files, long Bytes, DateTimeOffset DeletedAt, string? DeletedBy); + +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + UseStringEnumConverter = true, IgnoreReadOnlyProperties = true)] +[JsonSerializable(typeof(TrashRecord))] +internal sealed partial class TrashJson : JsonSerializerContext; diff --git a/src/Titano.Server/Api/SequenceEndpoints.cs b/src/Titano.Server/Api/SequenceEndpoints.cs index af64e3cc..57fc2de5 100644 --- a/src/Titano.Server/Api/SequenceEndpoints.cs +++ b/src/Titano.Server/Api/SequenceEndpoints.cs @@ -3,7 +3,9 @@ using System.Globalization; using System.Text; using System.Text.Json; using Titano.Core.Model; +using Microsoft.AspNetCore.Mvc; using Titano.Data; +using Titano.Data.Archiving; using Titano.Data.Repositories; using Titano.Protocol; using Titano.Server.Configuration; @@ -141,30 +143,35 @@ public static class SequenceEndpoints } /// - /// Removes a sequence from the index and moves its folder into the archive's trash (BRIEF §0.2 rule 8: nothing is - /// erased). ?dryRun=true only reports what would happen. Owners and admins only. + /// Moves a sequence's folder into the archive's trash and removes it from the index through the archive engine's + /// (BRIEF §0.2 rule 8: nothing is erased, the trash keeps it restorable). + /// ?dryRun=true only reports what would happen. Owners and admins only; a sequence a job is working on is refused (409). /// - private static async Task DeleteAsync(HttpContext context, Caller caller, Guid id, bool? dryRun, TitanoDatabase db, ServerArchive archive, - ServerOptions options, AuditLog audit, EventHub events) + private static async Task DeleteAsync(HttpContext context, Caller caller, Guid id, bool? dryRun, TitanoDatabase db, + [FromServices] ArchiveService? archives, AuditLog audit, EventHub events) { - if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); + var ct = context.RequestAborted; + 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 folder = string.IsNullOrEmpty(sequence.Folder) ? null : ArchivePathGuard.Resolve(archive.Root, sequence.Folder); - var trash = Path.Combine(options.TrashPath, id.ToString("N")); - var hasFolder = folder is not null && Directory.Exists(folder); - var plan = new SequenceDeletePlan(id, sequence.Folder, hasFolder ? Path.GetRelativePath(archive.Root, trash).Replace('\\', '/') : null, - sequence.FrameCount, sequence.TotalBytes, sequence.RenderedCount, dryRun == true); - if (dryRun == true) return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan); - - if (hasFolder) + var trash = archives?.Trash ?? new SequenceTrash(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner }); + DeletePlan plan; + try { - Directory.CreateDirectory(options.TrashPath); - Directory.Move(folder!, trash); + plan = await trash.PlanAsync([id], ct); + if (plan.Blocked is [{ } blocked]) return ApiErrors.Conflict(context, "sequence_busy", blocked.Reason.ToString()); + if (dryRun != true) await trash.DeleteAsync(plan, caller.User.Username, null, ct); } - await db.Sequences.DeleteAsync(id, context.RequestAborted); + catch (StaleDeletePlanException) + { + return ApiErrors.Conflict(context, "sequence_busy"); + } + var step = plan.Steps[0]; + var result = new SequenceDeletePlan(id, sequence.Folder, step.TrashFolder, sequence.FrameCount, sequence.TotalBytes, sequence.RenderedCount, dryRun == true); + if (dryRun == true) return Results.Json(result, ProtocolJson.Default.SequenceDeletePlan); + await audit.WriteAsync(caller, context, "sequence_deleted", "sequence", id.ToString(), sequence.DisplayTitle); events.Publish(new SequenceChangedEvent(id, "deleted", sequence.FramesVersion, sequence.SettingsVersion)); - return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan); + return Results.Json(result, ProtocolJson.Default.SequenceDeletePlan); } /// Everything a client needs to mirror a sequence and detect changes (BRIEF §14.5); ETag over the version counters. diff --git a/tests/Titano.Data.Tests/Archiving/ArchiveFixture.cs b/tests/Titano.Data.Tests/Archiving/ArchiveFixture.cs index 8635995f..1d1aea42 100644 --- a/tests/Titano.Data.Tests/Archiving/ArchiveFixture.cs +++ b/tests/Titano.Data.Tests/Archiving/ArchiveFixture.cs @@ -33,9 +33,10 @@ internal sealed class ArchiveFixture : IAsyncDisposable public ArchivePaths Paths => new(Archive.RootPath); public CancellationToken Ct => _context.Cancellation; - public static async Task CreateAsync(TestContext context, string? root = null) + /// The index to use (a PostgreSQL schema); a temporary SQLite file when null. + public static async Task CreateAsync(TestContext context, string? root = null, DatabaseOptions? database = null) { - var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "titano.db")), context.Cancellation); + var db = await TitanoDatabase.OpenAsync(database ?? DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "titano.db")), context.Cancellation); var service = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }); var archive = await service.AdoptAsync(root ?? context.CreateTempDirectory("archive"), "Main", context.Cancellation); return new ArchiveFixture(context, db, service, archive); diff --git a/tests/Titano.Data.Tests/Archiving/SequenceTrashTests.cs b/tests/Titano.Data.Tests/Archiving/SequenceTrashTests.cs new file mode 100644 index 00000000..0d5632a5 --- /dev/null +++ b/tests/Titano.Data.Tests/Archiving/SequenceTrashTests.cs @@ -0,0 +1,241 @@ +using Titano.Core.Archiving; +using Titano.Core.Model; +using Titano.Data.Archiving; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; +using static Titano.Data.Tests.Archiving.ArchiveFixture; + +namespace Titano.Data.Tests.Archiving; + +/// Deleting sequences into the archive's trash and restoring them (BRIEF §0.2 rule 8, §12.2, §12.5). +[Category("archive")] +public abstract class SequenceTrashTests(TestContext context) : DatabaseTest(context) +{ + private async Task FixtureAsync() => Own(await CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true))); + + /// Three scanned sequences in inbox/a, inbox/b and inbox/c, by folder. + private static async Task> PopulateAsync(ArchiveFixture fx) + { + Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "a"), Start, 3); + Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "b"), Start.AddDays(1), 3, firstSeed: 10); + Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "c"), Start.AddDays(2), 3, firstSeed: 20); + await fx.ScanAsync(); + var sequences = new List(); + foreach (var location in (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).OrderBy(l => l.Folder)) + sequences.Add((await fx.Db.Sequences.GetAsync(location.Id))!); + return sequences; + } + + private static (int Files, long Bytes) OnDisk(string folder) + { + var files = new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories).ToList(); + return (files.Count, files.Sum(f => f.Length)); + } + + /// One render of the sequence, stored in its exports folder. + private static async Task RenderAsync(ArchiveFixture fx, Sequence sequence) + { + var relative = sequence.Folder + "/exports/preview.mp4"; + var path = fx.Paths.FromRelative(relative); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + await File.WriteAllBytesAsync(path, new byte[1234]); + var render = new Render + { + Id = Guid.CreateVersion7(), + SequenceId = sequence.Id, + PresetName = "720p preview", + OutputPath = relative, + Codec = "h264", + Width = 1280, + Height = 720, + Fps = 30, + DurationSeconds = 2, + Bytes = 1234, + Created = new DateTimeOffset(2026, 10, 1, 9, 0, 0, TimeSpan.Zero), + }; + await fx.Db.Renders.InsertAsync(render); + return render; + } + + [Test] + public async Task TheDryRunCountsWhatMovesAndChangesNothing() + { + var fx = await FixtureAsync(); + var sequences = await PopulateAsync(fx); + var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id); + var folder = fx.Paths.Sequence(sequences[0].Folder).Folder; + + var plan = await fx.Service.PlanDeleteAsync([sequences[0].Id, sequences[1].Id], fx.Ct); + Assert.Empty(plan.Blocked); + Assert.Count(2, plan.Steps); + var (files, bytes) = OnDisk(folder); + Assert.Equal(files, plan.Steps[0].Files); + Assert.Equal(bytes, plan.Steps[0].Bytes); + Assert.Equal($".titano/trash/{sequences[0].Id:N}", plan.Steps[0].TrashFolder); + Assert.Equal(6, plan.Frames); + Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id)); + Assert.True(Directory.Exists(folder), "a dry run moves nothing"); + Assert.False(Directory.Exists(SequenceTrash.TrashDirectory(fx.Paths))); + } + + [Test] + public async Task DeletingMovesTheWholeFolderToTheTrashAndDropsTheRows() + { + var fx = await FixtureAsync(); + var sequences = await PopulateAsync(fx); + var victim = sequences[1]; + await RenderAsync(fx, victim); + var folder = fx.Paths.Sequence(victim.Folder).Folder; + var (files, bytes) = OnDisk(folder); + + var plan = await fx.Service.PlanDeleteAsync([victim.Id], fx.Ct); + var entries = await fx.Service.DeleteAsync(plan, "alberto", null, fx.Ct); + + var entry = Assert.Contains(entries, e => e.SequenceId == victim.Id); + Assert.False(Directory.Exists(folder)); + var trashed = Path.Combine(SequenceTrash.TrashDirectory(fx.Paths), entry.Name); + Assert.Equal((files, bytes), OnDisk(trashed)); + Assert.Equal(victim.Id, ManifestStore.ReadSequence(fx.Paths.Sequence(fx.Paths.ToRelative(trashed)).ManifestPath).Id); + Assert.Null(await fx.Db.Sequences.GetAsync(victim.Id)); + Assert.Empty(await fx.Db.Frames.ListBySequenceAsync(victim.Id)); + Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(victim.Id)); + Assert.NotNull(await fx.Db.Sequences.GetAsync(sequences[0].Id)); + + var listed = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.SequenceId == victim.Id); + Assert.Equal("inbox/b", listed.Folder); + Assert.Equal(3, listed.Frames); + Assert.Equal("alberto", listed.DeletedBy); + + // The trash is hidden from scans: nothing comes back on its own. + var scan = await fx.ScanAsync(ScanMode.Full); + Assert.Equal(2, scan.Folders); + Assert.Null(await fx.Db.Sequences.GetAsync(victim.Id)); + } + + [Test] + public async Task RestoringBringsBackTheSameIndexRowsAndRenders() + { + var fx = await FixtureAsync(); + var sequences = await PopulateAsync(fx); + var victim = sequences[0]; + await fx.Db.Sequences.EditAsync(victim.Id, new Titano.Data.Repositories.SequenceEdit { SettingsJson = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":41}}}""" }, null); + var render = await RenderAsync(fx, victim); + var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id); + var settings = (await fx.Db.Sequences.GetAsync(victim.Id))!.SettingsJson; + + var entry = (await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([victim.Id], fx.Ct), null, null, fx.Ct)).Single(); + var restored = Assert.NotNull(await fx.Service.RestoreAsync(fx.Archive.Id, entry.Name, fx.Ct)); + + Assert.Equal(victim.Folder, restored.Folder); + Assert.Equal(settings, restored.SettingsJson); + Assert.Equal(1, restored.RenderedCount); + Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id)); + Assert.Equal(render.OutputPath, (await fx.Db.Renders.ListBySequenceAsync(victim.Id)).Single().OutputPath); + Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)); + Assert.Empty(Directory.EnumerateFileSystemEntries(SequenceTrash.TrashDirectory(fx.Paths))); + Assert.Equal(0, (await fx.ScanAsync()).Indexed); + + // Deleted again: the trash takes it again under the same name. + var again = (await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([victim.Id], fx.Ct), null, null, fx.Ct)).Single(); + Assert.Equal(entry.Name, again.Name); + } + + [Test] + public async Task ARestoreIntoATakenFolderUsesAFreeOneAndKeepsRendersReachable() + { + var fx = await FixtureAsync(); + var sequences = await PopulateAsync(fx); + var victim = sequences[2]; + await RenderAsync(fx, victim); + var entry = (await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([victim.Id], fx.Ct), null, null, fx.Ct)).Single(); + Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "c"), Start.AddDays(5), 2, firstSeed: 40); + await fx.ScanAsync(); + + var restored = Assert.NotNull(await fx.Service.RestoreAsync(fx.Archive.Id, entry.Name, fx.Ct)); + Assert.Equal("inbox/c (2)", restored.Folder); + var output = (await fx.Db.Renders.ListBySequenceAsync(victim.Id)).Single().OutputPath; + Assert.Equal("inbox/c (2)/exports/preview.mp4", output); + Assert.FileExists(fx.Paths.FromRelative(output)); + foreach (var frame in await fx.Db.Frames.ListBySequenceAsync(victim.Id)) Assert.FileExists(fx.Paths.FromRelative(frame.RelativePath)); + Assert.Count(4, await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)); + } + + [Test] + public async Task SequencesThatCannotMoveAreBlockedAndUntouched() + { + var fx = await FixtureAsync(); + var sequences = await PopulateAsync(fx); + Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "a", "night"), Start.AddDays(3), 2, firstSeed: 30); + await fx.ScanAsync(); + var running = new Job + { + Id = Guid.CreateVersion7(), + Kind = JobKind.Proxies, + TargetIds = [sequences[1].Id], + State = JobState.Running, + NodeId = "test#0", + Created = DateTimeOffset.UtcNow, + Started = DateTimeOffset.UtcNow, + }; + await fx.Db.Jobs.EnqueueAsync(running); + // The folder of the third sequence now holds the sidecar of another sequence (copied over by hand). + File.Copy(fx.Paths.Sequence(sequences[0].Folder).ManifestPath, fx.Paths.Sequence(sequences[2].Folder).ManifestPath, overwrite: true); + + var plan = await fx.Service.PlanDeleteAsync([.. sequences.Select(s => s.Id)], fx.Ct); + Assert.Empty(plan.Steps); + Assert.SequenceEqual([DeleteBlock.ContainsSequences, DeleteBlock.Busy, DeleteBlock.ForeignSidecar], + plan.Blocked.OrderBy(b => b.Sequence.Folder, StringComparer.Ordinal).Select(b => b.Reason)); + } + + [Test] + public async Task APhotoFolderAdoptedAtTheRootNeverMoves() + { + var root = Context.CreateTempDirectory("adopted"); + Photos.WriteSeries(root, Start, 2); + var fx = Own(await CreateAsync(Context, root, await NewOptionsAsync(multiConnection: true))); + await fx.ScanAsync(); + var location = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(); + Assert.Equal(string.Empty, location.Folder); + + var plan = await fx.Service.PlanDeleteAsync([location.Id], fx.Ct); + Assert.Equal(DeleteBlock.ArchiveRoot, plan.Blocked.Single().Reason); + } + + [Test] + public async Task AStalePlanIsRefusedBeforeAnythingMoves() + { + var fx = await FixtureAsync(); + var sequences = await PopulateAsync(fx); + var plan = await fx.Service.PlanDeleteAsync([sequences[0].Id, sequences[1].Id], fx.Ct); + await fx.Service.ApplyRenameAsync(await fx.Service.PlanRenameAsync(fx.Archive.Id, [sequences[1].Id], "moved/{date}", null, fx.Ct), null, fx.Ct); + + var stale = await Assert.ThrowsAsync(() => fx.Service.DeleteAsync(plan, null, null, fx.Ct)); + Assert.Equal(sequences[1].Id, stale.SequenceId); + Assert.True(Directory.Exists(fx.Paths.Sequence(sequences[0].Folder).Folder)); + Assert.NotNull(await fx.Db.Sequences.GetAsync(sequences[0].Id)); + } + + [Test] + public async Task ARowWithoutAFolderLeavesOnlyTheIndex() + { + var fx = await FixtureAsync(); + var sequences = await PopulateAsync(fx); + Directory.Delete(fx.Paths.Sequence(sequences[0].Folder).Folder, recursive: true); + + var plan = await fx.Service.PlanDeleteAsync([sequences[0].Id], fx.Ct); + Assert.Null(plan.Steps.Single().TrashFolder); + Assert.Empty(await fx.Service.DeleteAsync(plan, null, null, fx.Ct)); + Assert.Null(await fx.Db.Sequences.GetAsync(sequences[0].Id)); + } +} + +public sealed class SqliteSequenceTrashTests(TestContext context) : SequenceTrashTests(context) +{ + protected override Backend Backend => Backend.SqliteFile; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresSequenceTrashTests(TestContext context) : SequenceTrashTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Server.Tests/Api/SequenceTests.cs b/tests/Titano.Server.Tests/Api/SequenceTests.cs index abcddbac..3fbeb2b2 100644 --- a/tests/Titano.Server.Tests/Api/SequenceTests.cs +++ b/tests/Titano.Server.Tests/Api/SequenceTests.cs @@ -149,6 +149,30 @@ public sealed class SequenceTests(TestContext context) await gone.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found"); } + [Test] + public async Task ASequenceAJobWorksOnIsNotDeleted() + { + await using var server = await TestServer.StartAsync(context); + var (editor, _, _) = await server.UserAsync("alberto", "editor"); + var frame = await Uploads.UploadAsync(editor, Uploads.Photo(3000, 35)); + var sequence = (await server.Database.Sequences.GetAsync(frame.SequenceId))!; + await server.Database.Jobs.EnqueueAsync(new Titano.Core.Model.Job + { + Id = Guid.CreateVersion7(), + Kind = Titano.Core.Model.JobKind.Render, + TargetIds = [sequence.Id], + State = Titano.Core.Model.JobState.Running, + NodeId = "node#0", + Created = DateTimeOffset.UtcNow, + Started = DateTimeOffset.UtcNow, + }); + + using (var plan = await editor.DeleteAsync($"/api/v1/sequences/{sequence.Id}?dryRun=true")) await plan.ExpectErrorAsync(HttpStatusCode.Conflict, "sequence_busy"); + using (var deleted = await editor.DeleteAsync($"/api/v1/sequences/{sequence.Id}")) await deleted.ExpectErrorAsync(HttpStatusCode.Conflict, "sequence_busy"); + Assert.True(Directory.Exists(Path.Combine(server.Options.ArchivePath, sequence.Folder))); + Assert.NotNull(await server.Database.Sequences.GetAsync(sequence.Id)); + } + [Test] public async Task FramesAndStatsArePaged() { From 20b9654c33054540cb078c93b2c23fadf89e1247 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 3 Oct 2026 11:50:43 +0000 Subject: [PATCH 02/18] feat(app): complete the Library: timeline, saved views, quick and mass actions, remote cards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Library gets a third layout (year bands of photos per month over the card grid; a month narrows to its year and scrolls to it), saved views stored as app-scope settings rows, hover quick actions on cards and rows (open, analyse, render the sequence's preset, sync), the full mass actions bar (analyse, proxies, verify, tags, rating, move, upload, download, delete into the trash, CSV) with each button's reason when it cannot run, and, while signed in, the server's sequences without a local copy as remote cards filterable by origin. Delete shows the engine's dry run behind a typed confirmation and offers Undo; the Archive manager gets Delete… and a Trash dialog that restores sequences. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Archive.resx | 36 + i18n/en/Library.resx | 49 ++ i18n/en/Tooltips.resx | 51 ++ i18n/it/Archive.it.resx | 35 + i18n/it/Library.it.resx | 49 ++ i18n/it/Server.it.resx | 2 +- i18n/it/Tooltips.it.resx | 51 ++ src/Titano.App/Archive/ArchiveDialogs.xaml | 177 +++++ src/Titano.App/Archive/DeletePlans.cs | 47 ++ src/Titano.App/Archive/SequenceDeletion.cs | 78 ++ .../Archive/TrashDialogViewModel.cs | 109 +++ src/Titano.App/Infrastructure/AppSettings.cs | 3 + src/Titano.App/Library/LibraryActions.cs | 217 ++++++ src/Titano.App/Library/LibraryFilter.cs | 55 +- src/Titano.App/Library/LibraryTimeline.cs | 63 ++ src/Titano.App/Library/MassActions.cs | 126 ++++ src/Titano.App/Library/RemoteCards.cs | 109 +++ src/Titano.App/Library/RemoteThumbnails.cs | 87 +++ src/Titano.App/Library/SavedViews.cs | 91 +++ src/Titano.App/Library/SequenceItem.cs | 57 +- src/Titano.App/Library/ThumbnailService.cs | 4 +- .../Library/ViewNameDialogViewModel.cs | 52 ++ src/Titano.App/Sections/ArchiveView.xaml | 183 +---- src/Titano.App/Sections/ArchiveViewModel.cs | 30 +- src/Titano.App/Sections/LibraryView.xaml | 524 +++++++++----- src/Titano.App/Sections/LibraryView.xaml.cs | 54 +- src/Titano.App/Sections/LibraryViewModel.cs | 665 ++++++++++++++++-- 27 files changed, 2582 insertions(+), 422 deletions(-) create mode 100644 src/Titano.App/Archive/ArchiveDialogs.xaml create mode 100644 src/Titano.App/Archive/DeletePlans.cs create mode 100644 src/Titano.App/Archive/SequenceDeletion.cs create mode 100644 src/Titano.App/Archive/TrashDialogViewModel.cs create mode 100644 src/Titano.App/Library/LibraryActions.cs create mode 100644 src/Titano.App/Library/LibraryTimeline.cs create mode 100644 src/Titano.App/Library/MassActions.cs create mode 100644 src/Titano.App/Library/RemoteCards.cs create mode 100644 src/Titano.App/Library/RemoteThumbnails.cs create mode 100644 src/Titano.App/Library/SavedViews.cs create mode 100644 src/Titano.App/Library/ViewNameDialogViewModel.cs diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx index 2b9444d0..35b8275d 100644 --- a/i18n/en/Archive.resx +++ b/i18n/en/Archive.resx @@ -34,7 +34,31 @@ Remove {0} from the index?long Its sidecar is gone. Only the index row is removed; no file is deleted.long Folder to copy into the archivelong + Move to trash + Not moved: {0} · {1}long + {0:N0} sequence moved to the trashlong + {0:N0} sequences moved to the trashlong + The sequences could not move to the trashlong + {0:N0} file + {0:N0} files + Move {0:N0} sequence to the trash?long + Move {0:N0} sequences to the trash?long + Keep + They stay in the archive's trash, restorable from Maintenance.long + {0} · {1} · {2}invariant + {0} and {1} ({2}) leave the library and move to the archive's trash; nothing is erased.long + + {0:N0} morelong + + {0:N0} morelong + Nothing can move to the trashlong + its photos are the archive rootlong + a job is working on itlong + other sequences are inside its folderlong + its folder holds another sequence; scan the archive firstlong + the archive is offline or read-onlylong + Type {0} to confirmlong + Undo Cancel + Close {0:N0} copy {0:N0} copies Folder @@ -98,6 +122,7 @@ Rebuild proxies Relink moved archive… Run maintenance + Trash… {0:N0} issue {0:N0} issues The orphan search stoppedlong @@ -153,6 +178,7 @@ {0:N0} sequences · all Analyse Clear filter + Delete… Export CSV Set filter Filtered set @@ -182,6 +208,16 @@ Rebuild index… Scan Verify + Deleted {0}long + The trash is emptylong + The sequence could not come back from the trashlong + Trash · {0}long + Deleted sequences + Reading the trash… + Restore + {0:N0} sequence restoredlong + {0:N0} sequences restoredlong + Restoring {0}…long Archive tree Undated Maintenance diff --git a/i18n/en/Library.resx b/i18n/en/Library.resx index cc92b057..92208d8b 100644 --- a/i18n/en/Library.resx +++ b/i18n/en/Library.resx @@ -6,12 +6,32 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Analyse Clear selection + Delete… + Download Export list Folder + Move… Open Proxies + Rating + Render + Sync + Tags… + Upload Verify Adopt a folder + Move works on the sequences of one archive at a time.long + The same on this PC and on the server: nothing to sync.long + Your server account cannot download originals.long + The library index is not open.long + Select one or more sequences first.long + Your server account cannot change this sequence.long + Your server account cannot upload.long + Sign in to a Titano Server first, on the Server screen.long + The selected sequences have nothing to fetch from the server.long + The server already has what the selected sequences hold.long + Only for sequences on this PC; the selection lives on the server.long + A transfer of this sequence is already under way.long Clear filters Camera Date @@ -32,10 +52,14 @@ Show Export the list to All cameras + This PC and server Any status All tags All years Camera + Origin + On this PC + Only on server Status Analysed Without proxies @@ -48,7 +72,13 @@ Year {0} s No sequences match the filters + The server did not accept the joblong {0} queued · {1} + Sent to the server: {0} · {1}long + The rating could not be savedlong + No rating + {0:N0} star + {0:N0} stars Rescan Search title, camera, tag {0:N0} selected @@ -65,7 +95,26 @@ Proxies Remote Synced + {0:N0} transfer queuedlong + {0:N0} transfers queuedlong View Grid List + Timeline + Saved views + Show view + Delete view + View {0} deletedlong + Give the view a name.long + At most {0} characters, no control characters.long + Another view already has this name.long + Name + Rename view + Rename view… + View renamed to {0}long + Save + Save view + Save view… + View {0} savedlong + Undo diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 2601110d..1109f1c3 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -29,6 +29,11 @@ Show every sequence of the selection again Close without changing anything · Esc Hide the sequences of this year + Move {0:N0} sequence to the trash; type the number above first + Move {0:N0} sequences to the trash; type the number above first + Change nothing + What moves to the archive's trash, and what cannot move + Bring the sequences back from the trash into their folders Show the folder of the first copy in Explorer Open the sequence of the first copy in the editor Find identical photos across sequences by hash · reads the index only @@ -72,6 +77,7 @@ Incremental scan: new, changed and removed files by modification time and size The selected years and sequences (all when nothing is selected), narrowed by camera, status or tag Run the deep analysis on every sequence in the set + Move the set to the archive's trash · shows the dry run, then asks you to type to confirm Export the set as CSV: one row per sequence Move the set into a new folder layout · dry run first Generate or refresh proxies @@ -84,6 +90,8 @@ Tags to add, separated by commas Tags to remove, separated by commas Title template; the title token is the current title · checked as you type + The sequences deleted from this archive, each one restorable + Move this sequence back into its folder and the library, with its settings and renders Re-hash every original and report bit rot · reads the whole archive {0} · Right arrow opens the year, Left arrow closes it Dismiss @@ -306,10 +314,40 @@ Cards with thumbnails Copy and verify photos from a memory card Table with sortable columns + Deep analysis of {0:N0} sequence on this PC · runs as one job + Deep analysis of {0:N0} sequences on this PC · runs as one job + Move {0:N0} sequence to its archive's trash · shows the dry run, then asks you to type to confirm + Move {0:N0} sequences to their archive's trash · shows the dry run, then asks you to type to confirm + Fetch what {0:N0} sequence lacks here (originals or renders) from the server · runs as a transfer job + Fetch what {0:N0} sequences lack here (originals or renders) from the server · runs as transfer jobs + Save {0:N0} row as CSV in a folder you choose + Save {0:N0} rows as CSV in a folder you choose + Move {0:N0} sequence into a new folder layout of its archive · shows the dry run first + Move {0:N0} sequences into a new folder layout of their archive · shows the dry run first + Build JPEG proxies of {0:N0} sequence · runs as one job + Build JPEG proxies of {0:N0} sequences · runs as one job + Set the rating of {0:N0} sequence, in its sidecar and the index + Set the rating of {0:N0} sequences, in their sidecars and the index + Add or remove tags on {0:N0} sequence + Add or remove tags on {0:N0} sequences + Send what the server lacks of {0:N0} sequence (originals and settings, or renders) · runs as a transfer job + Send what the server lacks of {0:N0} sequences (originals and settings, or renders) · runs as transfer jobs + Re-read {0:N0} sequence and compare every hash with the index · runs as a job + Re-read {0:N0} sequences and compare every hash with the index · runs as a job per archive Open in the sequence editor · Enter Use an existing archive folder on this PC or the network + Show the sequences on this PC, only those on the server, or both Build JPEG proxies for fast editing · runs as a job Build proxies of the selected sequences · runs as one job + Queue a render with {0}, this sequence's recommended or default preset · runs as a job + Render with {0} on the server, where the originals are · the server or a render node runs it + Fetch the server's originals this PC lacks, verified by hash · runs as a transfer job + Fetch the server's renders this sequence lacks · runs as a transfer job + Settings changed here and on the server; choose what to keep on the Server screen + Send the renders of this sequence the server lacks · runs as a transfer job + Send or take the settings changed on one side + Send the originals and settings the server lacks · runs as a transfer job + Give the selection this rating Rescan the archive for changes · runs as a job Click selects · double-click opens Search titles, camera makes and models, and tags as you type @@ -337,8 +375,21 @@ {0:N0} warning; open the sequence for details {0:N0} warnings; open the sequence for details Show only one tag + Year bands with photos per month above the cards + Click a month to show its year and scroll to its sequences Re-read every file and compare its hash with the index · runs as a job Verify the hashes of the selected sequences · runs as one job + Show the search, filters and sort saved under this name + Forget the saved view on screen; no sequence is touched + A short name, such as "Night, 4K, not analysed" + Give the saved view on screen another name + Rename the view · Enter + Save the search, filters and sort on screen as a named view + Save the view · Enter + Save the deleted view again + Saved views: show one, or save the filters on screen + Saved view on screen: {0} + Choose a saved view to show Show only one year of first capture Version, diagnostics and links Scan, verify and maintain the archive · Ctrl+4 diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx index d219e873..5a828515 100644 --- a/i18n/it/Archive.it.resx +++ b/i18n/it/Archive.it.resx @@ -31,7 +31,30 @@ Rimuovere {0} dall'indice? Il suo sidecar non c'è più. Viene rimossa solo la riga dell'indice; nessun file viene eliminato. Cartella da copiare nell'archivio + Sposta nel cestino + Non spostata: {0} · {1} + {0:N0} sequenza spostata nel cestino + {0:N0} sequenze spostate nel cestino + Impossibile spostare le sequenze nel cestino + {0:N0} file + {0:N0} file + Spostare {0:N0} sequenza nel cestino? + Spostare {0:N0} sequenze nel cestino? + Mantieni + Restano nel cestino dell'archivio, ripristinabili da Manutenzione. + {0} e {1} ({2}) escono dalla libreria e vanno nel cestino dell'archivio; non viene cancellato nulla. + + {0:N0} altra + + altre {0:N0} + Niente può andare nel cestino + le sue foto sono la radice dell'archivio + un'attività ci sta lavorando + altre sequenze stanno nella sua cartella + la sua cartella contiene un'altra sequenza; prima esegui una scansione + l'archivio non è raggiungibile o è di sola lettura + Digita {0} per confermare + Annulla Annulla + Chiudi {0:N0} copia {0:N0} copie Cartella @@ -94,6 +117,7 @@ Ricrea proxy Ricollega archivio spostato… Esegui manutenzione + Cestino… {0:N0} problema {0:N0} problemi Ricerca degli orfani interrotta @@ -148,6 +172,7 @@ {0:N0} sequenze · tutte Analizza Togli filtro + Elimina… Esporta CSV Filtro selezione Selezione @@ -176,6 +201,16 @@ Ricostruisci indice… Scansiona Verifica + Eliminata il {0} + Il cestino è vuoto + Impossibile ripristinare la sequenza dal cestino + Cestino · {0} + Sequenze eliminate + Lettura del cestino… + Ripristina + {0:N0} sequenza ripristinata + {0:N0} sequenze ripristinate + Ripristino di {0}… Albero dell'archivio Senza data Manutenzione diff --git a/i18n/it/Library.it.resx b/i18n/it/Library.it.resx index 5d75b9af..4265f7ad 100644 --- a/i18n/it/Library.it.resx +++ b/i18n/it/Library.it.resx @@ -6,12 +6,32 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Analizza Deseleziona tutto + Elimina… + Scarica Esporta elenco Cartella + Sposta… Apri Proxy + Voto + Renderizza + Sincronizza + Tag… + Carica Verifica Adotta una cartella + Lo spostamento agisce sulle sequenze di un solo archivio alla volta. + Uguale su questo PC e sul server: niente da sincronizzare. + Il tuo account sul server non può scaricare gli originali. + L'indice della libreria non è aperto. + Prima seleziona una o più sequenze. + Il tuo account sul server non può modificare questa sequenza. + Il tuo account sul server non può caricare. + Prima accedi a un Titano Server, nella schermata Server. + Le sequenze selezionate non hanno nulla da ricevere dal server. + Il server ha già tutto ciò che contengono le sequenze selezionate. + Solo per sequenze su questo PC; la selezione si trova sul server. + Un trasferimento di questa sequenza è già in corso. Azzera i filtri Fotocamera Data @@ -32,10 +52,14 @@ Mostra Esporta l'elenco in Tutte le fotocamere + Questo PC e server Qualsiasi stato Tutti i tag Tutti gli anni Fotocamera + Origine + Su questo PC + Solo sul server Stato Analizzate Senza proxy @@ -48,7 +72,13 @@ Anno {0} s Nessuna sequenza corrisponde + Il server non ha accettato l'attività {0} in coda · {1} + Inviato al server: {0} · {1} + Impossibile salvare il voto + Nessun voto + {0:N0} stella + {0:N0} stelle Ripeti scansione Cerca titolo, fotocamera, tag {0:N0} selezionata @@ -65,7 +95,26 @@ Proxy Remota Sincronizzata + {0:N0} trasferimento in coda + {0:N0} trasferimenti in coda Vista Griglia Elenco + Cronologia + Viste salvate + Mostra vista + Elimina vista + Vista {0} eliminata + Dai un nome alla vista. + Al massimo {0} caratteri, senza caratteri di controllo. + Un'altra vista ha già questo nome. + Nome + Rinomina vista + Rinomina vista… + Vista rinominata in {0} + Salva + Salva vista + Salva vista… + Vista {0} salvata + Annulla diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index 27661ba8..aaf6c9ae 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -64,7 +64,7 @@ Troppi tentativi; attendi un minuto e riprova. Scegli una password diversa da quella attuale. Non puoi farlo sul tuo account. - Un job sta lavorando su questa sequenza, oppure non può andare nel cestino; riprova quando è libera. + Un'attività sta lavorando su questa sequenza, oppure non può andare nel cestino; riprova quando è libera. La sessione è scaduta; accedi di nuovo. È impostato da una variabile d'ambiente; modificala lì. La sequenza è cambiata sul server; ricaricala e riapplica la modifica. diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 2d899232..9c563bb1 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -29,6 +29,11 @@ Mostra di nuovo tutte le sequenze della selezione Chiudi senza modificare nulla · Esc Nascondi le sequenze di quest'anno + Sposta {0:N0} sequenza nel cestino; prima digita il numero indicato + Sposta {0:N0} sequenze nel cestino; prima digita il numero indicato + Non cambiare nulla + Cosa va nel cestino dell'archivio e cosa non può spostarsi + Riporta le sequenze dal cestino nelle loro cartelle Mostra in Esplora risorse la cartella della prima copia Apri nell'editor la sequenza della prima copia Trova foto identiche tra le sequenze tramite hash · legge solo l'indice @@ -72,6 +77,7 @@ Scansione incrementale: file nuovi, modificati e rimossi per data e dimensione Anni e sequenze selezionati (tutti se nulla è selezionato), ristretti per fotocamera, stato o tag Esegui l'analisi profonda su ogni sequenza della selezione + Sposta la selezione nel cestino dell'archivio · mostra prima la simulazione, poi chiede di digitare per confermare Esporta la selezione in CSV: una riga per sequenza Sposta la selezione in una nuova struttura di cartelle · prima la simulazione Crea o aggiorna i proxy @@ -84,6 +90,8 @@ Tag da aggiungere, separati da virgole Tag da rimuovere, separati da virgole Modello del titolo; il segnaposto title è il titolo attuale · controllato mentre scrivi + Le sequenze eliminate da questo archivio, ognuna ripristinabile + Riporta questa sequenza nella sua cartella e nella libreria, con impostazioni e render Ricalcola l'hash di ogni originale e segnala i danni · legge tutto l'archivio {0} · Freccia destra apre l'anno, freccia sinistra lo chiude Chiudi @@ -306,10 +314,40 @@ Schede con miniature Copia e verifica le foto da una scheda di memoria Tabella con colonne ordinabili + Analisi approfondita di {0:N0} sequenza su questo PC · un'unica attività + Analisi approfondita di {0:N0} sequenze su questo PC · un'unica attività + Sposta {0:N0} sequenza nel cestino del suo archivio · mostra prima la simulazione, poi chiede di digitare per confermare + Sposta {0:N0} sequenze nel cestino del loro archivio · mostra prima la simulazione, poi chiede di digitare per confermare + Ricevi dal server ciò che manca qui a {0:N0} sequenza (originali o render) · come attività di trasferimento + Ricevi dal server ciò che manca qui a {0:N0} sequenze (originali o render) · come attività di trasferimento + Salva {0:N0} riga come CSV in una cartella a tua scelta + Salva {0:N0} righe come CSV in una cartella a tua scelta + Sposta {0:N0} sequenza in una nuova struttura di cartelle del suo archivio · prima la simulazione + Sposta {0:N0} sequenze in una nuova struttura di cartelle del loro archivio · prima la simulazione + Crea i proxy JPEG di {0:N0} sequenza · un'unica attività + Crea i proxy JPEG di {0:N0} sequenze · un'unica attività + Imposta il voto di {0:N0} sequenza, nel sidecar e nell'indice + Imposta il voto di {0:N0} sequenze, nei sidecar e nell'indice + Aggiungi o rimuovi tag su {0:N0} sequenza + Aggiungi o rimuovi tag su {0:N0} sequenze + Invia ciò che manca al server di {0:N0} sequenza (originali e impostazioni, o render) · come attività di trasferimento + Invia ciò che manca al server di {0:N0} sequenze (originali e impostazioni, o render) · come attività di trasferimento + Rileggi {0:N0} sequenza e confronta ogni hash con l'indice · come attività + Rileggi {0:N0} sequenze e confronta ogni hash con l'indice · un'attività per archivio Apre nell'editor della sequenza · Invio Usa una cartella archivio esistente su questo PC o in rete + Mostra le sequenze su questo PC, solo quelle sul server o entrambe Crea proxy JPEG per una modifica veloce · viene eseguita come attività Crea i proxy delle sequenze selezionate · un'unica attività + Metti in coda un render con {0}, il preset consigliato o predefinito della sequenza · come attività + Renderizza con {0} sul server, dove sono gli originali · lo esegue il server o un nodo di render + Scarica gli originali del server che mancano su questo PC, verificati con l'hash · come attività di trasferimento + Ricevi i render del server che mancano a questa sequenza · come attività di trasferimento + Impostazioni cambiate qui e sul server; scegli cosa tenere nella schermata Server + Invia i render di questa sequenza che mancano al server · come attività di trasferimento + Invia o ricevi le impostazioni cambiate da una sola parte + Invia gli originali e le impostazioni che mancano al server · come attività di trasferimento + Assegna questo voto alla selezione Ripete la scansione dell'archivio per trovare modifiche · viene eseguita come attività Clic seleziona · doppio clic apre Cerca titoli, marche e modelli di fotocamera e tag mentre scrivi @@ -337,8 +375,21 @@ {0:N0} avviso; apri la sequenza per i dettagli {0:N0} avvisi; apri la sequenza per i dettagli Mostra un solo tag + Fasce per anno con le foto di ogni mese sopra le schede + Fai clic su un mese per mostrarne l'anno e scorrere alle sue sequenze Rilegge ogni file e ne confronta l'hash con l'indice · viene eseguita come attività Verifica gli hash delle sequenze selezionate · un'unica attività + Mostra la ricerca, i filtri e l'ordinamento salvati con questo nome + Dimentica la vista salvata sullo schermo; nessuna sequenza viene toccata + Un nome breve, ad esempio "Notte, 4K, non analizzate" + Dai un altro nome alla vista salvata sullo schermo + Rinomina la vista · Invio + Salva ricerca, filtri e ordinamento sullo schermo come vista con nome + Salva la vista · Invio + Salva di nuovo la vista eliminata + Viste salvate: mostrane una o salva i filtri sullo schermo + Vista salvata sullo schermo: {0} + Scegli una vista salvata da mostrare Mostra un solo anno del primo scatto Versione, diagnostica e collegamenti Scansiona, verifica e gestisci l'archivio · Ctrl+4 diff --git a/src/Titano.App/Archive/ArchiveDialogs.xaml b/src/Titano.App/Archive/ArchiveDialogs.xaml new file mode 100644 index 00000000..0c5a6f52 --- /dev/null +++ b/src/Titano.App/Archive/ArchiveDialogs.xaml @@ -0,0 +1,177 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - +