E2: correzioni della revisione delle copie esterne
- Nome libero scelto prima di scrivere, libero sul disco e nel database; una riga orfana sul nome diventa «Tolto» (guardando il suo percorso, anche se differisce solo per le maiuscole): prima la copia finiva «Non riuscito» con il file già scritto, o toglieva la copia buona. - «Controlla le copie» rilegge la radice e riguarda i file mancanti; con il disco staccato si ferma e mette in pausa senza segnare nulla. - Su Linux lo spostamento sul nome finale non sostituisce mai un file (renameat2 RENAME_NOREPLACE, poi link e unlink). - Le copie in coda di un lavoro interrotto diventano «Interrotta» e si riprendono; il permesso dei lavori lunghi si tiene già nel piano. - «Superato» con il file di nuovo in libreria: filtro, piano e «Copia di nuovo» d'accordo; l'adozione ravviva la riga invece di fallire. - «Una copia sola» con una regola sola in filtro, piano, visualizzatore e copiatore (solo copie di un altro account in cartelle in uso). - Controllo della cartella per identità vera (percorso finale, realpath, dispositivo di mountinfo): riconosce collegamenti e bind mount di una sottocartella della libreria. - Sfoglia delle cartelle con tempi massimi; «Nessuna cartella» solo se non ce n'è; «In copia…» nel visualizzatore; numero e fuoco stabili in «Copia di nuovo anche…»; una sola lettura per volta nella Dashboard. - Prove dell'interfaccia indipendenti dall'ora e dal file scelto; prove nuove in ExportReviewTests, ExportFolderCheckTests, ExportRootTests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
28c7f814b1
commit
36ad5c6f9d
28 files changed
+1314
-112
No files matched your search
@@ -271,10 +271,19 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = current.Id, RelativePath = copied, Note = null, LastError = null }, bytes, copied).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The file is not there: «Tolto», unless the whole destination went away meanwhile.
|
||||
if (!Directory.Exists(root) && await ProbeAsync(x, ct).ConfigureAwait(false) is { } gone)
|
||||
// The file is not there: «Tolto», unless the whole destination went away meanwhile. A root that was away
|
||||
// for a moment and answers the probe again is asked once more for the file before it is called «Tolto».
|
||||
if (!Directory.Exists(root))
|
||||
{
|
||||
return ItemResult.Paused(gone);
|
||||
if (await ProbeAsync(x, ct).ConfigureAwait(false) is { } gone)
|
||||
{
|
||||
return ItemResult.Paused(gone);
|
||||
}
|
||||
|
||||
if (current.RelativePath is { } back && Exists(root, back))
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = current.Id, RelativePath = back, Note = null, LastError = null }, bytes, back).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false);
|
||||
@@ -303,8 +312,7 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
}
|
||||
|
||||
if (x.OneOnly
|
||||
&& await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, ct).ConfigureAwait(false) is { AccountId: { } other, RelativePath: { } elsewherePath } elsewhere
|
||||
&& other != accountId
|
||||
&& await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, accountId, ct).ConfigureAwait(false) is { RelativePath: { } elsewherePath } elsewhere
|
||||
&& await x.DestinationAsync(storage, elsewhere.DestinationId, ct).ConfigureAwait(false) is { IsRetired: false } where
|
||||
&& Exists(where.RootPath, elsewherePath))
|
||||
{
|
||||
@@ -366,14 +374,23 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
|
||||
if (holder.Identity == file.Identity)
|
||||
{
|
||||
if (holder.State == ExportCopyState.Superseded)
|
||||
{
|
||||
// Our own bytes, recorded as superseded (the file came back to the library without the change that
|
||||
// would have revived the row): the copy is copied, not superseded, and must not stay stuck.
|
||||
return await ReviveAsync(item, file, failed, holder, candidate).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = candidate, Note = null, LastError = null }, file.Bytes, candidate).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The same bytes, recorded for another copy: not ours to take.
|
||||
}
|
||||
|
||||
// A path recorded for another copy whose file is gone is free again («Tolto»).
|
||||
await ReleaseStalePathAsync(destination, planned, file.Identity, ct).ConfigureAwait(false);
|
||||
// The name the record can take: free on the disk and in the database. A path recorded for another copy whose
|
||||
// file is gone is free again («Tolto»); one whose file is there under another letter case (a case-sensitive
|
||||
// disk) is not, and the next numbered name is tried.
|
||||
var chosen = await ChooseNameAsync(destination, planned, ct).ConfigureAwait(false);
|
||||
|
||||
// The intent, in its own transaction, before the .part exists (WP1.8 cleans only the folders of items).
|
||||
item = item with { RelativePath = planned };
|
||||
@@ -389,7 +406,7 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
root,
|
||||
directory,
|
||||
(digest, _) => string.Equals(digest.Sha256, file.Sha256, StringComparison.Ordinal)
|
||||
? ValueTask.FromResult<string?>(planned)
|
||||
? ValueTask.FromResult<string?>(chosen)
|
||||
: throw new ContentChangedException("Il file della libreria non corrisponde a quello registrato."),
|
||||
new SafeWriteOptions
|
||||
{
|
||||
@@ -420,14 +437,90 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
return await FailAsync(item, file, failed, ExportText.ErrorText(ex), null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
string? taken = null;
|
||||
if (!string.Equals(saved.RelativePath, planned, StringComparison.Ordinal))
|
||||
var taken = string.Equals(saved.RelativePath, planned, StringComparison.Ordinal) ? null : ExportText.Notes.NameTaken;
|
||||
|
||||
// The writer moved the file onto a name where no file was: a row still holding that path is stale (decision of
|
||||
// 2026-11-27), also when the name is the one chosen, since a row could appear meanwhile.
|
||||
await ReleaseStalePathAsync(destination, saved.RelativePath, justWritten: true, ct).ConfigureAwait(false);
|
||||
return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, ExportCopyOrigin.Written, taken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first of the planned path and its numbered names (numbered as the writer numbers them) that is free on the
|
||||
/// disk and free, or stale, in the database; the planned path when none is found (the writer then decides).
|
||||
/// </summary>
|
||||
private async Task<string> ChooseNameAsync(ExportDestination destination, string planned, CancellationToken ct)
|
||||
{
|
||||
for (var attempt = 1; attempt <= MaxSiblings; attempt++)
|
||||
{
|
||||
taken = ExportText.Notes.NameTaken;
|
||||
await ReleaseStalePathAsync(destination, saved.RelativePath, file.Identity, ct).ConfigureAwait(false);
|
||||
string name;
|
||||
try
|
||||
{
|
||||
name = ExportPaths.NumberedName(destination.RootPath, planned, attempt, MaxPath);
|
||||
}
|
||||
catch (PathTooLongException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (Exists(destination.RootPath, name))
|
||||
{
|
||||
continue; // the writer would not take it either
|
||||
}
|
||||
|
||||
if (await ReleaseStalePathAsync(destination, name, justWritten: false, ct).ConfigureAwait(false))
|
||||
{
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, ExportCopyOrigin.Written, taken).ConfigureAwait(false);
|
||||
return planned;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A Copied or Superseded row on this path (matched without regard to case, as its unique index) whose file is not
|
||||
/// there becomes «Tolto». The row's own stored path is the one tested: on a case-sensitive disk another letter case
|
||||
/// is another file. With <paramref name="justWritten"/> this job has just written the file at exactly
|
||||
/// <paramref name="path"/>, where no file was, so a row with exactly that path is stale without a look. Returns
|
||||
/// whether the path is free in the database now.
|
||||
/// </summary>
|
||||
private async Task<bool> ReleaseStalePathAsync(ExportDestination destination, string path, bool justWritten, CancellationToken ct)
|
||||
{
|
||||
var held = await _env.Storage.Exports.FindCopyByPathAsync(destination.Id, path, ct).ConfigureAwait(false);
|
||||
if (held is null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var stale = held.RelativePath is not { } stored
|
||||
|| (justWritten && string.Equals(stored, path, StringComparison.Ordinal))
|
||||
|| !Exists(destination.RootPath, stored);
|
||||
if (!stale)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await _env.Storage.Exports.UpdateCopyAsync(held with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A Superseded row of this very identity whose bytes are at its path: it becomes the Copied row again. When the
|
||||
/// identity has a current «Non riuscito» row, that one becomes the Copied row and the old one stays as history.
|
||||
/// </summary>
|
||||
private async Task<ItemResult> ReviveAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy holder, string path)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var none = CancellationToken.None;
|
||||
var now = _env.Clock.Now;
|
||||
if (failed is null && await exports.FindCurrentCopyAsync(file.Identity, none).ConfigureAwait(false) is null)
|
||||
{
|
||||
await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Copied, SupersededBySha256 = null, MediaId = file.Media.Id, StateChangedAt = now }, none).ConfigureAwait(false);
|
||||
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = path, Note = null, LastError = null }, file.Bytes, path).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Removed, StateChangedAt = now }, none).ConfigureAwait(false);
|
||||
return await RecordAsync(item, file, failed, null, path, file.Bytes, ExportCopyOrigin.Adopted, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Files to look at for adoption: the planned path, then the one recorded before a crash and its numbered names.</summary>
|
||||
@@ -468,16 +561,6 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A Copied or Superseded row of another copy on this path whose file is not there becomes «Tolto».</summary>
|
||||
private async Task ReleaseStalePathAsync(ExportDestination destination, string path, ExportCopyIdentity identity, CancellationToken ct)
|
||||
{
|
||||
var held = await _env.Storage.Exports.FindCopyByPathAsync(destination.Id, path, ct).ConfigureAwait(false);
|
||||
if (held is not null && held.Identity != identity && !Exists(destination.RootPath, path))
|
||||
{
|
||||
await _env.Storage.Exports.UpdateCopyAsync(held with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ItemResult> RecordAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy? orphan, string path, long bytes, ExportCopyOrigin origin, string? note)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
|
||||
@@ -263,10 +263,60 @@ public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout =
|
||||
}
|
||||
}
|
||||
|
||||
// Then where the folders really are (links, junctions, drive aliases, bind mounts), read-only; the probe stays
|
||||
// for what this cannot see (a share that points back to this computer).
|
||||
if (IdentityOverlap(full, shown, context.Protected) is { } aliased)
|
||||
{
|
||||
return new ExportFolderVerdict(full, aliased);
|
||||
}
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return ProbeIdentity(full, shown, context.Protected);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The identity comparison (decision of 2026-11-27): the candidate is a protected folder, or inside one, when its
|
||||
/// <see cref="FolderLocation"/> is; it contains one when the protected folder's location is inside the candidate's, or
|
||||
/// inside (or around) what a mount below the candidate shows.
|
||||
/// </summary>
|
||||
private ExportFolderProblem? IdentityOverlap(string full, string shown, IReadOnlyList<ProtectedFolder> protectedFolders)
|
||||
{
|
||||
if (FolderIdentity.Locate(full, _mounts, out var real) is not { } candidate || real is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var below = _mounts.All()
|
||||
.Where(m => !ExportPaths.Same(m.MountPoint, real) && ExportPaths.IsSameOrInside(m.MountPoint, real))
|
||||
.Select(FolderIdentity.Of)
|
||||
.OfType<FolderLocation>()
|
||||
.ToList();
|
||||
foreach (var folder in protectedFolders)
|
||||
{
|
||||
if (FolderIdentity.Locate(folder.Path, _mounts) is not { } location)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (candidate.IsSame(location))
|
||||
{
|
||||
return Same(shown, folder);
|
||||
}
|
||||
|
||||
if (candidate.IsSameOrInside(location))
|
||||
{
|
||||
return Inside(shown, folder);
|
||||
}
|
||||
|
||||
if (location.IsSameOrInside(candidate) || below.Any(b => location.IsSameOrInside(b) || b.IsSameOrInside(location)))
|
||||
{
|
||||
return Contains(shown, folder);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static ExportFolderProblem? Overlap(string full, string protectedPath, string shown, ProtectedFolder folder)
|
||||
{
|
||||
if (ExportPaths.Same(full, protectedPath))
|
||||
|
||||
@@ -40,6 +40,10 @@ public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain
|
||||
/// <param name="NotExported">«Esporta questo account» off, no destination, or a content type the destination does not take.</param>
|
||||
/// <param name="Missing">«File non presente in libreria».</param>
|
||||
/// <param name="Destinations">Each destination that gets files, with whether it answers now.</param>
|
||||
/// <param name="HasDestination">
|
||||
/// A folder of the copies exists (the general one or one of an account, in use): when nothing is to copy, the dialog
|
||||
/// says «no folder» only when this is false, not because no destination gets files.
|
||||
/// </param>
|
||||
public sealed record ExportPlan(
|
||||
int Files,
|
||||
long Bytes,
|
||||
@@ -47,7 +51,8 @@ public sealed record ExportPlan(
|
||||
int RemovedOrSuperseded,
|
||||
int NotExported,
|
||||
int Missing,
|
||||
IReadOnlyList<ExportPlanDestination> Destinations)
|
||||
IReadOnlyList<ExportPlanDestination> Destinations,
|
||||
bool HasDestination = true)
|
||||
{
|
||||
public static ExportPlan Empty { get; } = new(0, 0, 0, 0, 0, 0, []);
|
||||
}
|
||||
|
||||
@@ -103,8 +103,7 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
||||
? new PlannedFile(c, destination, PlannedCopy.Write, Again: true)
|
||||
: new PlannedFile(c, destination, PlannedCopy.RemovedOrSuperseded);
|
||||
}
|
||||
else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, ct).ConfigureAwait(false) is { } other
|
||||
&& other.AccountId != c.AccountId)
|
||||
else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, c.AccountId, ct).ConfigureAwait(false) is not null)
|
||||
{
|
||||
planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied);
|
||||
}
|
||||
@@ -230,7 +229,8 @@ internal sealed class PlanTally
|
||||
list.Add(new ExportPlanDestination(d.Id, ExportDestinations.Label(d), d.RootPath, d.Scope, username, files, bytes, d.PausedAt is not null, problem, free));
|
||||
}
|
||||
|
||||
return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list);
|
||||
var any = rows.Count > 0 || (await env.Storage.Exports.ListDestinationsAsync(false, ct).ConfigureAwait(false)).Count > 0;
|
||||
return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list, any);
|
||||
}
|
||||
|
||||
/// <summary>Destinations that get a run: those with files to write, already copied, or «tolti o superati».</summary>
|
||||
|
||||
@@ -8,7 +8,11 @@ namespace Febe.Core.Export;
|
||||
/// <param name="Root">Folder of its file system shown there (<c>/</c>: the root of that file system).</param>
|
||||
/// <param name="FileSystemType">File system type (<c>vfat</c> for FAT32).</param>
|
||||
/// <param name="ReadOnly">Mounted read-only.</param>
|
||||
public sealed record ExportMount(string MountPoint, string Root, string FileSystemType, bool ReadOnly);
|
||||
/// <param name="Device">
|
||||
/// The device of its file system (<c>major:minor</c> in <c>mountinfo</c>), or null when unknown: with it the identity
|
||||
/// test of the folder check sees a bind mount of a folder of the library (decision of 2026-11-27).
|
||||
/// </param>
|
||||
public sealed record ExportMount(string MountPoint, string Root, string FileSystemType, bool ReadOnly, string? Device = null);
|
||||
|
||||
/// <summary>The mount table (a seam: tests give their own; Linux reads <c>/proc/self/mountinfo</c>).</summary>
|
||||
public interface IExportMounts
|
||||
@@ -46,7 +50,7 @@ public sealed class ProcMountInfo(Func<string?>? read = null) : IExportMounts
|
||||
}
|
||||
}
|
||||
|
||||
private static ExportMount? Map(MountInfoEntry? m) => m is null ? null : new ExportMount(m.MountPoint, m.Root, m.FileSystemType, m.ReadOnly);
|
||||
private static ExportMount? Map(MountInfoEntry? m) => m is null ? null : new ExportMount(m.MountPoint, m.Root, m.FileSystemType, m.ReadOnly, m.Device);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -153,6 +157,54 @@ public static class ExportRoots
|
||||
/// </summary>
|
||||
/// <exception cref="ExportFolderException">The folder cannot be browsed.</exception>
|
||||
public static IReadOnlyList<SourceFolderChoice> Browse(ExportRootOptions o, string? relative)
|
||||
{
|
||||
var folder = BrowsedFolder(o, relative);
|
||||
return [.. Subfolders(o, folder).Select(s => s.Choice with { HasSubfolders = HasSubfolders(s.FullPath) })];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Browse"/> for the web picker, never blocking it (spec §4.10 «I controlli sul disco esterno sono asincroni
|
||||
/// e brevi»): the listing of the folder gets <paramref name="timeout"/>, and each subfolder gets as much in parallel to
|
||||
/// tell whether it has subfolders, so a dead share mounted below the folder shows without the arrow instead of
|
||||
/// hiding the healthy ones.
|
||||
/// </summary>
|
||||
/// <exception cref="ExportFolderException">The folder cannot be browsed, or does not answer in time.</exception>
|
||||
public static Task<IReadOnlyList<SourceFolderChoice>> BrowseAsync(ExportRootOptions o, string? relative, TimeSpan timeout, CancellationToken ct) =>
|
||||
BrowseAsync(o, relative, timeout, HasSubfolders, ct);
|
||||
|
||||
/// <summary><see cref="BrowseAsync(ExportRootOptions, string?, TimeSpan, CancellationToken)"/> with the look into a subfolder given (a seam for tests).</summary>
|
||||
internal static async Task<IReadOnlyList<SourceFolderChoice>> BrowseAsync(ExportRootOptions o, string? relative, TimeSpan timeout, Func<string, bool> hasSubfolders, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(hasSubfolders);
|
||||
var folder = BrowsedFolder(o, relative);
|
||||
IReadOnlyList<Subfolder> subfolders;
|
||||
try
|
||||
{
|
||||
subfolders = await Task.Run(() => Subfolders(o, folder), ct).WaitAsync(timeout, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
throw new ExportFolderException(
|
||||
$"La cartella {DisplayPath(o, folder)} non risponde entro {timeout.TotalSeconds:0} secondi: controlla che il disco o la condivisione siano collegati, poi riprova.",
|
||||
ExportFolderProblemKind.NotResponding);
|
||||
}
|
||||
|
||||
async Task<SourceFolderChoice> LookAsync(Subfolder s)
|
||||
{
|
||||
try
|
||||
{
|
||||
return s.Choice with { HasSubfolders = await Task.Run(() => hasSubfolders(s.FullPath), ct).WaitAsync(timeout, ct).ConfigureAwait(false) };
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
return s.Choice; // it does not answer: shown, without the arrow
|
||||
}
|
||||
}
|
||||
|
||||
return await Task.WhenAll(subfolders.Select(LookAsync)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static string BrowsedFolder(ExportRootOptions o, string? relative)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(o);
|
||||
string folder;
|
||||
@@ -169,6 +221,12 @@ public static class ExportRoots
|
||||
folder = ExportPaths.Trim(Path.GetFullPath(relative));
|
||||
}
|
||||
|
||||
return folder;
|
||||
}
|
||||
|
||||
/// <summary>The subfolders of a folder, sorted, without looking into them.</summary>
|
||||
private static List<Subfolder> Subfolders(ExportRootOptions o, string folder)
|
||||
{
|
||||
if (!Directory.Exists(folder))
|
||||
{
|
||||
throw new ExportFolderException($"La cartella {DisplayPath(o, folder)} non esiste.", ExportFolderProblemKind.Missing);
|
||||
@@ -178,10 +236,7 @@ public static class ExportRoots
|
||||
{
|
||||
return Directory.EnumerateDirectories(folder, "*", ImportSources.Enumeration(recursive: false))
|
||||
.Order(StringComparer.Ordinal)
|
||||
.Select(d => new SourceFolderChoice(
|
||||
Path.GetFileName(d),
|
||||
o.Root is { } r ? LibraryLayout.ToStored(Path.GetRelativePath(r, d)) : d,
|
||||
Directory.EnumerateDirectories(d, "*", ImportSources.Enumeration(recursive: false)).Any()))
|
||||
.Select(d => new Subfolder(d, new SourceFolderChoice(Path.GetFileName(d), o.Root is { } r ? LibraryLayout.ToStored(Path.GetRelativePath(r, d)) : d, false)))
|
||||
.ToList();
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
@@ -190,6 +245,22 @@ public static class ExportRoots
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The folder has a subfolder to open (false when it cannot be read).</summary>
|
||||
private static bool HasSubfolders(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Directory.EnumerateDirectories(folder, "*", ImportSources.Enumeration(recursive: false)).Any();
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A subfolder found by the picker, with its full path.</summary>
|
||||
private sealed record Subfolder(string FullPath, SourceFolderChoice Choice);
|
||||
|
||||
/// <summary>
|
||||
/// The full path of a chosen folder: in Docker the root plus a relative path (or a full path inside the root), never
|
||||
/// the root itself, never with «..»; without a root a fully qualified path.
|
||||
|
||||
@@ -117,15 +117,29 @@ public sealed class ExportService : IAsyncDisposable
|
||||
public async Task<ExportStart> StartAsync(ExportJobRequest request, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var held = new LeaseHolder();
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureIdle();
|
||||
|
||||
// The long-work gate is held from the plan on (§4.10 «esportazione, importazione e ricostruzione non girano
|
||||
// insieme»): a rebuild or an import cannot start while the runs and their items are being recorded.
|
||||
if (_env.Gate is { } gate)
|
||||
{
|
||||
if (!gate.TryEnter(LongWorkKind.Export, out var lease, out var busy))
|
||||
{
|
||||
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value));
|
||||
}
|
||||
|
||||
held.Lease = lease;
|
||||
}
|
||||
|
||||
_starting = true; // a second «Copia in…» meanwhile records nothing
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return await StartReservedAsync(request, ct).ConfigureAwait(false);
|
||||
return await StartReservedAsync(request, held, ct).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -133,10 +147,12 @@ public sealed class ExportService : IAsyncDisposable
|
||||
{
|
||||
_starting = false;
|
||||
}
|
||||
|
||||
held.Lease?.Dispose(); // not handed to a job: nothing to copy, or the start failed
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ExportStart> StartReservedAsync(ExportJobRequest request, CancellationToken ct)
|
||||
private async Task<ExportStart> StartReservedAsync(ExportJobRequest request, LeaseHolder held, CancellationToken ct)
|
||||
{
|
||||
var effective = await Destinations.ResolveAllAsync(ct).ConfigureAwait(false);
|
||||
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
||||
@@ -206,7 +222,8 @@ public sealed class ExportService : IAsyncDisposable
|
||||
lock (_gate)
|
||||
{
|
||||
_starting = false;
|
||||
StartCopyJob(ordered.Select(r => r.Id).ToList());
|
||||
StartCopyJob(ordered.Select(r => r.Id).ToList(), held.Lease);
|
||||
held.Lease = null; // the job owns it now
|
||||
}
|
||||
}
|
||||
catch
|
||||
@@ -463,26 +480,37 @@ public sealed class ExportService : IAsyncDisposable
|
||||
}
|
||||
|
||||
after = page[^1].Id;
|
||||
if (!Directory.Exists(destination.RootPath))
|
||||
if (!await RootAnswersAsync(destination, ct).ConfigureAwait(false))
|
||||
{
|
||||
// The disk went away during the check: nothing is «Tolto» because of that.
|
||||
var gone = await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) ?? $"{label} non è raggiungibile.";
|
||||
await ExportPause.PauseAsync(_env, destination, gone).ConfigureAwait(false);
|
||||
await PauseCheckAsync(destination, label, ct).ConfigureAwait(false);
|
||||
Report(ExportPhase.Finished, done);
|
||||
return;
|
||||
}
|
||||
|
||||
var missing = new List<long>();
|
||||
var missing = new List<ExportCopy>();
|
||||
foreach (var copy in page)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (copy.RelativePath is not { } path || !FileExists(destination.RootPath, path))
|
||||
{
|
||||
missing.Add(copy.Id);
|
||||
missing.Add(copy);
|
||||
}
|
||||
}
|
||||
|
||||
removed += await exports.MarkCopiesRemovedAsync(missing, _env.Clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
// The disk may have gone away while the page was read (decision of 2026-11-27, §4.10): the root is asked
|
||||
// again after the files and before anything is marked, and a missing file is looked for once more.
|
||||
if (missing.Count > 0 && !await RootAnswersAsync(destination, ct).ConfigureAwait(false))
|
||||
{
|
||||
await PauseCheckAsync(destination, label, ct).ConfigureAwait(false);
|
||||
Report(ExportPhase.Finished, done);
|
||||
return;
|
||||
}
|
||||
|
||||
var gone = missing
|
||||
.Where(copy => copy.RelativePath is not { } path || !FileExists(destination.RootPath, path))
|
||||
.Select(copy => copy.Id)
|
||||
.ToList();
|
||||
removed += await exports.MarkCopiesRemovedAsync(gone, _env.Clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
done += page.Count;
|
||||
Report(ExportPhase.Checking, done);
|
||||
}
|
||||
@@ -501,6 +529,26 @@ public sealed class ExportService : IAsyncDisposable
|
||||
Report(ExportPhase.Finished, done);
|
||||
}
|
||||
|
||||
/// <summary>The root of the destination is there, asked within the folder-check time (a dead share must not block).</summary>
|
||||
private async Task<bool> RootAnswersAsync(ExportDestination destination, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await Task.Run(() => Directory.Exists(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The disk went away during «Controlla le copie»: nothing is «Tolto» because of that, the destination pauses.</summary>
|
||||
private async Task PauseCheckAsync(ExportDestination destination, string label, CancellationToken ct)
|
||||
{
|
||||
var problem = await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) ?? $"{label} non è raggiungibile.";
|
||||
await ExportPause.PauseAsync(_env, destination, problem).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private bool FileExists(string root, string relativePath)
|
||||
{
|
||||
try
|
||||
@@ -561,25 +609,59 @@ public sealed class ExportService : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private void StartCopyJob(IReadOnlyList<long> runIds) =>
|
||||
StartJob(runIds, async (progress, token) =>
|
||||
{
|
||||
foreach (var runId in runIds)
|
||||
private void StartCopyJob(IReadOnlyList<long> runIds, IDisposable? lease = null) =>
|
||||
StartJob(
|
||||
runIds,
|
||||
async (progress, token) =>
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var next = 0;
|
||||
try
|
||||
{
|
||||
await Copier.CopyAsync(runId, progress, token).ConfigureAwait(false);
|
||||
for (; next < runIds.Count; next++)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
await Copier.CopyAsync(runIds[next], progress, token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested)
|
||||
{
|
||||
// Stored with the run (Interrupted, with its error); the next destination still gets its files.
|
||||
LastJobError = ExportText.ErrorText(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested)
|
||||
finally
|
||||
{
|
||||
// Stored with the run (Interrupted, with its error); the next destination still gets its files.
|
||||
LastJobError = ExportText.ErrorText(ex);
|
||||
// «Interrompi» (or «Annulla», or the end of Febe) stopped the job before its later destinations: those
|
||||
// runs were recorded as running and nothing runs them now. They become «interrotto», resumable, as
|
||||
// RecoverAsync would make them at the next start.
|
||||
await InterruptQueuedAsync(runIds.Skip(next)).ConfigureAwait(false);
|
||||
}
|
||||
},
|
||||
lease);
|
||||
|
||||
/// <summary>Runs of a stopped job that were never reached and are still recorded as running become «interrotto».</summary>
|
||||
private async Task InterruptQueuedAsync(IEnumerable<long> runIds)
|
||||
{
|
||||
foreach (var runId in runIds)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (await _env.Storage.Exports.GetRunAsync(runId, CancellationToken.None).ConfigureAwait(false) is { State: ExportRunState.Running } run)
|
||||
{
|
||||
await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Interrupted, LastError = null }, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// RecoverAsync makes it «interrotto» at the next start.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void StartJob(IReadOnlyList<long> runIds, Func<IProgress<ExportProgress>, CancellationToken, Task> work)
|
||||
/// <summary>Starts a job; <paramref name="held"/> is a lease of the gate already taken (the job owns it once started).</summary>
|
||||
private void StartJob(IReadOnlyList<long> runIds, Func<IProgress<ExportProgress>, CancellationToken, Task> work, IDisposable? held = null)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
@@ -588,8 +670,8 @@ public sealed class ExportService : IAsyncDisposable
|
||||
throw new InvalidOperationException(BusyText);
|
||||
}
|
||||
|
||||
IDisposable? lease = null;
|
||||
if (_env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Export, out lease, out var busy))
|
||||
var lease = held;
|
||||
if (lease is null && _env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Export, out lease, out var busy))
|
||||
{
|
||||
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value));
|
||||
}
|
||||
@@ -662,6 +744,12 @@ public sealed class ExportService : IAsyncDisposable
|
||||
|
||||
private sealed record Job(IReadOnlyList<long> RunIds, CancellationTokenSource Cancellation, Task Task);
|
||||
|
||||
/// <summary>A lease of the long-work gate on its way from <see cref="StartAsync"/> to the job.</summary>
|
||||
private sealed class LeaseHolder
|
||||
{
|
||||
public IDisposable? Lease { get; set; }
|
||||
}
|
||||
|
||||
private sealed class Reporter(ExportService owner) : IProgress<ExportProgress>
|
||||
{
|
||||
private (ExportPhase, long?)? _phase;
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// Where a folder really is, whatever name it was reached by: the folder check compares these, read-only, besides its
|
||||
/// probe file (decision of 2026-11-27, widening spec §4.10 «Cartelle rifiutate»).
|
||||
/// <list type="bullet">
|
||||
/// <item>Windows: the final path of the folder (<c>GetFinalPathNameByHandle</c> on a handle opened without any access
|
||||
/// right), which resolves junctions, symbolic links, <c>subst</c> drives and mapped drives (to their UNC path);</item>
|
||||
/// <item>Linux: the real path (<c>realpath</c>, every symbolic link resolved), then, through the mount table, the
|
||||
/// device of its file system and the folder of that file system it is (a bind mount of a folder of the library in Docker
|
||||
/// is the same device, inside the root of the library's mount).</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
/// <param name="Device">The device of the file system (<c>major:minor</c>), or null: then <paramref name="Path"/> is a full path.</param>
|
||||
/// <param name="Path">With a device, the folder within its file system ('/' separated); else the real full path.</param>
|
||||
internal sealed record FolderLocation(string? Device, string Path)
|
||||
{
|
||||
/// <summary>This folder is <paramref name="other"/>.</summary>
|
||||
public bool IsSame(FolderLocation other) => Comparable(other) && (Device is null ? ExportPaths.Same(Path, other.Path) : string.Equals(Path, other.Path, ExportPaths.PathComparison));
|
||||
|
||||
/// <summary>This folder is <paramref name="other"/> or inside it.</summary>
|
||||
public bool IsSameOrInside(FolderLocation other) => Comparable(other) && (Device is null ? ExportPaths.IsSameOrInside(Path, other.Path) : InsidePosix(Path, other.Path));
|
||||
|
||||
private bool Comparable(FolderLocation other) => string.Equals(Device, other.Device, StringComparison.Ordinal);
|
||||
|
||||
private static bool InsidePosix(string path, string folder)
|
||||
{
|
||||
if (string.Equals(path, folder, ExportPaths.PathComparison) || folder == "/")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return path.StartsWith(folder.TrimEnd('/') + "/", ExportPaths.PathComparison);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Finds the <see cref="FolderLocation"/> of a folder (see there).</summary>
|
||||
internal static class FolderIdentity
|
||||
{
|
||||
private const uint FileShareAll = 0x1 | 0x2 | 0x4;
|
||||
private const uint OpenExisting = 3;
|
||||
private const uint FileFlagBackupSemantics = 0x02000000;
|
||||
|
||||
/// <summary>The location of an existing folder, or null when it cannot be told (missing, unreadable).</summary>
|
||||
public static FolderLocation? Locate(string fullPath, IExportMounts mounts) => Locate(fullPath, mounts, out _);
|
||||
|
||||
/// <summary>The location of an existing folder and its real path, or null when it cannot be told.</summary>
|
||||
public static FolderLocation? Locate(string fullPath, IExportMounts mounts, out string? real)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(mounts);
|
||||
real = RealPath(fullPath);
|
||||
if (real is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (mounts.FindContaining(real) is { Device: { Length: > 0 } device } mount)
|
||||
{
|
||||
var relative = Path.GetRelativePath(mount.MountPoint, real).Replace('\\', '/');
|
||||
var root = mount.Root.TrimEnd('/');
|
||||
return new FolderLocation(device, relative == "." ? (root.Length == 0 ? "/" : root) : $"{root}/{relative}");
|
||||
}
|
||||
|
||||
return new FolderLocation(null, real);
|
||||
}
|
||||
|
||||
/// <summary>The location of what a mount shows, when its device is known.</summary>
|
||||
public static FolderLocation? Of(ExportMount mount) =>
|
||||
mount.Device is { Length: > 0 } device ? new FolderLocation(device, mount.Root.Length > 1 ? mount.Root.TrimEnd('/') : mount.Root) : null;
|
||||
|
||||
/// <summary>The path of the folder with every link (and on Windows every drive alias) resolved, or null.</summary>
|
||||
internal static string? RealPath(string fullPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(fullPath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
return FinalPathWindows(fullPath);
|
||||
}
|
||||
|
||||
return RealPathUnix(fullPath);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException
|
||||
or EntryPointNotFoundException or DllNotFoundException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? FinalPathWindows(string fullPath)
|
||||
{
|
||||
// No access right is asked: only the identity of the folder is read, and nothing is ever written there.
|
||||
using var handle = CreateFileW(fullPath, 0, FileShareAll, IntPtr.Zero, OpenExisting, FileFlagBackupSemantics, IntPtr.Zero);
|
||||
if (handle.IsInvalid)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var buffer = new char[1024];
|
||||
var length = GetFinalPathNameByHandleW(handle, buffer, (uint)buffer.Length, 0);
|
||||
if (length >= buffer.Length)
|
||||
{
|
||||
buffer = new char[length + 1];
|
||||
length = GetFinalPathNameByHandleW(handle, buffer, (uint)buffer.Length, 0);
|
||||
}
|
||||
|
||||
if (length == 0 || length >= buffer.Length)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var path = new string(buffer, 0, (int)length);
|
||||
if (path.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
path = @"\\" + path[8..];
|
||||
}
|
||||
else if (path.StartsWith(@"\\?\", StringComparison.Ordinal))
|
||||
{
|
||||
path = path[4..];
|
||||
}
|
||||
|
||||
return ExportPaths.Trim(path);
|
||||
}
|
||||
|
||||
private static string? RealPathUnix(string fullPath)
|
||||
{
|
||||
var resolved = RealPathNative(fullPath, IntPtr.Zero);
|
||||
if (resolved == IntPtr.Zero)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return Marshal.PtrToStringUTF8(resolved) is { Length: > 0 } path ? ExportPaths.Trim(path) : null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Free(resolved);
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern SafeFileHandle CreateFileW(string fileName, uint desiredAccess, uint shareMode, IntPtr securityAttributes, uint creationDisposition, uint flagsAndAttributes, IntPtr templateFile);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern uint GetFinalPathNameByHandleW(SafeFileHandle file, [Out] char[] filePath, uint length, uint flags);
|
||||
|
||||
[DllImport("libc", EntryPoint = "realpath", SetLastError = true)]
|
||||
private static extern IntPtr RealPathNative([MarshalAs(UnmanagedType.LPUTF8Str)] string path, IntPtr resolved);
|
||||
|
||||
[DllImport("libc", EntryPoint = "free")]
|
||||
private static extern void Free(IntPtr pointer);
|
||||
}
|
||||
@@ -12,7 +12,9 @@ namespace Febe.Core.Library;
|
||||
/// <param name="Options">Per-mount options (<c>rw</c>, <c>ro</c>, <c>noatime</c>…).</param>
|
||||
/// <param name="FileSystemType">File system type (<c>ext4</c>, <c>vfat</c>, <c>cifs</c>…).</param>
|
||||
/// <param name="Source">Mount source (<c>/dev/sdb1</c>, <c>//server/share</c>…), unescaped.</param>
|
||||
public sealed record MountInfoEntry(int Id, int ParentId, string Root, string MountPoint, IReadOnlyList<string> Options, string FileSystemType, string Source)
|
||||
/// <param name="Device">The device of the file system, <c>major:minor</c> (field 3): two mounts with the same device show
|
||||
/// folders of one file system, so <see cref="Root"/> tells whether one is inside the other.</param>
|
||||
public sealed record MountInfoEntry(int Id, int ParentId, string Root, string MountPoint, IReadOnlyList<string> Options, string FileSystemType, string Source, string? Device = null)
|
||||
{
|
||||
/// <summary>The mount is read-only (<c>ro</c>, as for a Docker volume mounted with <c>:ro</c>).</summary>
|
||||
public bool ReadOnly => Options.Contains("ro", StringComparer.Ordinal);
|
||||
@@ -61,7 +63,8 @@ public static class MountInfoTable
|
||||
point,
|
||||
fields[5].Split(',', StringSplitOptions.RemoveEmptyEntries),
|
||||
fields[separator + 1],
|
||||
MountTable.Unescape(fields[separator + 2])));
|
||||
MountTable.Unescape(fields[separator + 2]),
|
||||
fields[2]));
|
||||
}
|
||||
|
||||
return entries;
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>What <see cref="NoReplaceRename.TryMove"/> did.</summary>
|
||||
internal enum NoReplaceOutcome
|
||||
{
|
||||
/// <summary>The file has its new name.</summary>
|
||||
Moved,
|
||||
|
||||
/// <summary>The new name exists: nothing changed.</summary>
|
||||
Taken,
|
||||
|
||||
/// <summary>The file system cannot do it atomically: nothing changed, the caller checks and moves.</summary>
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An atomic rename that never replaces an existing name, on Linux and the other Unix systems (rule 12: Febe never
|
||||
/// overwrites a file). On Unix <c>File.Move(overwrite: false)</c> checks and then calls rename(2), which replaces: another
|
||||
/// program, or another Febe writing to the same folder (spec §4.10 «due istanze sulla stessa cartella»), could create the
|
||||
/// name in between. Only the platform's own C library is called (BCL interop, no external component).
|
||||
/// <list type="number">
|
||||
/// <item>Linux: <c>renameat2(…, RENAME_NOREPLACE)</c>; EEXIST means the name is taken;</item>
|
||||
/// <item>without it (an older kernel, a file system that refuses the flag, another Unix): <c>link</c> then
|
||||
/// <c>unlink</c> of the temporary name, where link refuses an existing name with EEXIST;</item>
|
||||
/// <item>without hard links either (vfat, some CIFS mounts): <see cref="NoReplaceOutcome.Unsupported"/>.</item>
|
||||
/// </list>
|
||||
/// Not for Windows, where <c>MoveFileEx</c> without <c>MOVEFILE_REPLACE_EXISTING</c> already refuses an existing name.
|
||||
/// </summary>
|
||||
internal static class NoReplaceRename
|
||||
{
|
||||
private const int AtFdCwd = -100;
|
||||
private const uint RenameNoReplace = 1;
|
||||
private const int Eexist = 17; // the same value on Linux, macOS and the BSDs
|
||||
|
||||
private static volatile bool _noRenameAt2;
|
||||
private static volatile bool _noLink;
|
||||
|
||||
/// <summary>Renames <paramref name="source"/> to <paramref name="destination"/> unless that name exists.</summary>
|
||||
public static NoReplaceOutcome TryMove(string source, string destination)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(source);
|
||||
ArgumentException.ThrowIfNullOrEmpty(destination);
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
return NoReplaceOutcome.Unsupported;
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsLinux() && !_noRenameAt2)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (RenameAt2(AtFdCwd, source, AtFdCwd, destination, RenameNoReplace) == 0)
|
||||
{
|
||||
return NoReplaceOutcome.Moved;
|
||||
}
|
||||
|
||||
if (Marshal.GetLastPInvokeError() == Eexist)
|
||||
{
|
||||
return NoReplaceOutcome.Taken;
|
||||
}
|
||||
|
||||
// EINVAL (the file system refuses the flag), ENOSYS (an older kernel) or another error: try a link.
|
||||
}
|
||||
catch (Exception ex) when (ex is EntryPointNotFoundException or DllNotFoundException)
|
||||
{
|
||||
_noRenameAt2 = true; // a C library without renameat2
|
||||
}
|
||||
}
|
||||
|
||||
if (_noLink)
|
||||
{
|
||||
return NoReplaceOutcome.Unsupported;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (Link(source, destination) == 0)
|
||||
{
|
||||
_ = Unlink(source); // when this fails the caller's clean-up removes the temporary name
|
||||
return NoReplaceOutcome.Moved;
|
||||
}
|
||||
|
||||
// EPERM, ENOTSUP, EXDEV…: no hard links here. The caller checks and moves, and reports a real error itself.
|
||||
return Marshal.GetLastPInvokeError() == Eexist ? NoReplaceOutcome.Taken : NoReplaceOutcome.Unsupported;
|
||||
}
|
||||
catch (Exception ex) when (ex is EntryPointNotFoundException or DllNotFoundException)
|
||||
{
|
||||
_noLink = true;
|
||||
return NoReplaceOutcome.Unsupported;
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport("libc", EntryPoint = "renameat2", SetLastError = true)]
|
||||
private static extern int RenameAt2(
|
||||
int oldDirectory,
|
||||
[MarshalAs(UnmanagedType.LPUTF8Str)] string oldPath,
|
||||
int newDirectory,
|
||||
[MarshalAs(UnmanagedType.LPUTF8Str)] string newPath,
|
||||
uint flags);
|
||||
|
||||
[DllImport("libc", EntryPoint = "link", SetLastError = true)]
|
||||
private static extern int Link([MarshalAs(UnmanagedType.LPUTF8Str)] string oldPath, [MarshalAs(UnmanagedType.LPUTF8Str)] string newPath);
|
||||
|
||||
[DllImport("libc", EntryPoint = "unlink", SetLastError = true)]
|
||||
private static extern int Unlink([MarshalAs(UnmanagedType.LPUTF8Str)] string path);
|
||||
}
|
||||
@@ -330,11 +330,33 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!);
|
||||
|
||||
// On Unix File.Move(overwrite: false) checks for the destination and then renames, and a rename replaces:
|
||||
// two writers of this process could overwrite each other. The check and the rename are therefore done under
|
||||
// one lock (Febe is the only writer of its library). On Windows the move itself refuses an existing name.
|
||||
// another writer (of this process, another Febe on the same export folder, another program) could take the
|
||||
// name in between. On Unix the move is therefore an atomic rename that refuses an existing name
|
||||
// (NoReplaceRename); only where the file system cannot do that, the check and the move are done under one
|
||||
// lock, which still keeps the writers of this process apart. On Windows the move itself refuses an existing
|
||||
// name.
|
||||
lock (MoveGate)
|
||||
{
|
||||
if (File.Exists(finalPath) || Directory.Exists(finalPath))
|
||||
if (Directory.Exists(finalPath))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
var outcome = NoReplaceRename.TryMove(tempPath, finalPath);
|
||||
if (outcome == NoReplaceOutcome.Moved)
|
||||
{
|
||||
return finalPath;
|
||||
}
|
||||
|
||||
if (outcome == NoReplaceOutcome.Taken)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (File.Exists(finalPath))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -182,8 +182,13 @@ public interface IExportStore
|
||||
/// </summary>
|
||||
Task<ExportCopy?> FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
|
||||
|
||||
/// <summary>«Una copia sola»: the newest Copied row of this original, variant and format in a destination in use, any account.</summary>
|
||||
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, CancellationToken ct = default);
|
||||
/// <summary>
|
||||
/// «Una copia sola»: the newest Copied row of this original, variant and format in a destination in use (the general
|
||||
/// folder or the own folder of an account still in Febe), of an account still in Febe; with
|
||||
/// <paramref name="exceptAccountId"/>, of an account other than that one, so a newer row of the account itself never
|
||||
/// hides the copy of another account (decision of 2026-11-27: «una copia altrove conta solo se è di un altro account»).
|
||||
/// </summary>
|
||||
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The state of whole copies (<see cref="ExportVariant.Whole"/>, <see cref="ExportFormat.Original"/>) of (account,
|
||||
|
||||
@@ -115,7 +115,12 @@ internal static class ExportFilterSql
|
||||
return destination == "1" ? $"({Present})" : $"({Present} AND {destination})";
|
||||
}
|
||||
|
||||
/// <summary>The file is copied in its effective destination (or, with «Una copia sola», in any destination in use).</summary>
|
||||
/// <summary>
|
||||
/// The file is copied in its effective destination, or, with «Una copia sola», copied for another account still in
|
||||
/// Febe in a destination in use: the rule of the plan and of the copy (decision of 2026-11-27, «una copia altrove conta
|
||||
/// solo se è di un altro account»). A copy of the same account in a folder that is no longer its effective one, and a
|
||||
/// copy whose account was removed, do not count.
|
||||
/// </summary>
|
||||
public static string Copied(ExportFilterContext x)
|
||||
{
|
||||
if (!x.HasCopies)
|
||||
@@ -124,10 +129,14 @@ internal static class ExportFilterSql
|
||||
}
|
||||
|
||||
return x.SamePost == SamePostCopies.OneOnly
|
||||
? $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id IN ({InUse(x)}) AND c.state = 'Copied' AND c.variant <> 'Frame')"
|
||||
? $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id IN ({InUse(x)}) AND c.state = 'Copied' AND c.variant <> 'Frame' AND {OneOnlyMatch(x)})"
|
||||
: $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Copied' AND c.variant <> 'Frame')";
|
||||
}
|
||||
|
||||
/// <summary>«Una copia sola»: a copy <c>c</c> counts for the file of <c>e</c> (in a destination in use, tested apart).</summary>
|
||||
private static string OneOnlyMatch(ExportFilterContext x) =>
|
||||
$"((c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id) OR (c.account_id IS NOT NULL AND c.account_id <> e.account_id))";
|
||||
|
||||
/// <summary>The last copy of the file in its effective destination failed («Non riuscito»): «Copia in…» tries again.</summary>
|
||||
public static string Failed(ExportFilterContext x) => !x.HasFailed
|
||||
? "0"
|
||||
@@ -211,7 +220,7 @@ internal static class ExportFilterSql
|
||||
LibraryCopiesFilter.NotCopied => Files(NotCopied(x)),
|
||||
LibraryCopiesFilter.RemovedOrSuperseded => !x.HasHistory
|
||||
? "0"
|
||||
: $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = coalesce(c.superseded_by_sha256, c.source_sha256) "
|
||||
: $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 IN (c.source_sha256, c.superseded_by_sha256) "
|
||||
+ $"WHERE c.destination_id IN ({InUse(x)}) AND c.state IN ('Removed', 'Superseded')) AND {Files(Replaced(x))}",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null),
|
||||
};
|
||||
@@ -248,7 +257,7 @@ internal static class ExportFilterSql
|
||||
private static string CopiedEntries(ExportFilterContext x)
|
||||
{
|
||||
var match = x.SamePost == SamePostCopies.OneOnly
|
||||
? string.Empty
|
||||
? $" AND {OneOnlyMatch(x)}"
|
||||
: $" AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id";
|
||||
return "+e.id IN (SELECT m.entry_id FROM export_copy c CROSS JOIN media m CROSS JOIN entry e "
|
||||
+ $"WHERE c.destination_id IN ({InUse(x)}) AND c.state = 'Copied' AND c.variant <> 'Frame' AND m.sha256 = c.source_sha256 AND e.id = m.entry_id{match} "
|
||||
@@ -267,14 +276,17 @@ internal static class ExportFilterSql
|
||||
: Copied(x);
|
||||
|
||||
/// <summary>
|
||||
/// The removed or superseded part of <see cref="Replaced"/>: the copy of this file in the effective destination was
|
||||
/// removed, or a copy was superseded (or removed) by this file. In bulk each EXISTS sits behind its list of SHA-256.
|
||||
/// The removed or superseded part of <see cref="Replaced"/>: a copy of this very file in the effective destination
|
||||
/// was removed or superseded (whether or not it names the file that replaced it: the file can be back in the library
|
||||
/// in another entry), or a copy was superseded (or removed) by this file. The same rows as the plan reads
|
||||
/// (<c>GetCopyStatesAsync</c>), so filter, marks, counts and plan agree (D3). In bulk each EXISTS sits behind its list
|
||||
/// of SHA-256.
|
||||
/// </summary>
|
||||
private static string History(ExportFilterContext x, bool bulk)
|
||||
{
|
||||
var destination = DestinationOf(x);
|
||||
var removed = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
|
||||
+ "AND c.state = 'Removed' AND c.superseded_by_sha256 IS NULL)";
|
||||
+ "AND c.state IN ('Removed', 'Superseded'))";
|
||||
var superseded = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
|
||||
+ "AND c.state IN ('Superseded', 'Removed'))";
|
||||
if (!bulk)
|
||||
@@ -283,7 +295,7 @@ internal static class ExportFilterSql
|
||||
}
|
||||
|
||||
var inUse = InUse(x);
|
||||
return $"((m.sha256 IN (SELECT c.source_sha256 FROM export_copy c WHERE c.destination_id IN ({inUse}) AND c.state = 'Removed') AND {removed}) "
|
||||
return $"((m.sha256 IN (SELECT c.source_sha256 FROM export_copy c WHERE c.destination_id IN ({inUse}) AND c.state IN ('Removed', 'Superseded')) AND {removed}) "
|
||||
+ $"OR (m.sha256 IN (SELECT c.superseded_by_sha256 FROM export_copy c WHERE c.superseded_by_sha256 IS NOT NULL AND c.destination_id IN ({inUse})) AND {superseded}))";
|
||||
}
|
||||
|
||||
|
||||
@@ -885,7 +885,8 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
||||
internal const string CopiedElsewhereSql = $"""
|
||||
SELECT {CopyColumns} FROM export_copy
|
||||
WHERE source_sha256 = @h AND variant = @v AND format = @f AND state = 'Copied' AND account_id IS NOT NULL
|
||||
AND destination_id IN (SELECT id FROM export_destination WHERE removed_at IS NULL)
|
||||
AND (@a IS NULL OR account_id <> @a)
|
||||
AND destination_id IN (SELECT id FROM export_destination WHERE removed_at IS NULL AND (scope = 'General' OR account_id IS NOT NULL))
|
||||
ORDER BY id DESC LIMIT 1
|
||||
""";
|
||||
|
||||
@@ -947,11 +948,13 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, CancellationToken ct = default)
|
||||
public Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default)
|
||||
{
|
||||
var sha = ExportValues.Sha(sha256, nameof(sha256));
|
||||
return db.ReadAsync(
|
||||
c => ReadFirst(c.Command(CopiedElsewhereSql).With("@h", sha).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)), ReadCopy),
|
||||
c => ReadFirst(
|
||||
c.Command(CopiedElsewhereSql).With("@h", sha).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)).With("@a", Sql.Int(exceptAccountId)),
|
||||
ReadCopy),
|
||||
ct);
|
||||
}
|
||||
|
||||
|
||||
@@ -98,7 +98,8 @@ public static class ExportApi
|
||||
}
|
||||
|
||||
var relative = string.IsNullOrWhiteSpace(path) ? string.Empty : path.Trim().Trim('/', '\\').Replace('\\', '/');
|
||||
var folders = Guard(() => ExportRoots.Browse(root, relative.Length == 0 ? null : relative));
|
||||
// Never on the request thread without a limit: a dead share below /esporta must not hang the picker.
|
||||
var folders = await GuardAsync(() => ExportRoots.BrowseAsync(root, relative.Length == 0 ? null : relative, DiskTimeout, ct)).ConfigureAwait(false);
|
||||
string? parent = relative.Length == 0 ? null : relative.Contains('/', StringComparison.Ordinal) ? relative[..relative.LastIndexOf('/')] : string.Empty;
|
||||
var full = relative.Length == 0 ? rootFolder : Path.Combine(rootFolder, LibraryLayout.ToPlatform(relative));
|
||||
return ApiHttp.Json(
|
||||
@@ -253,8 +254,27 @@ public static class ExportApi
|
||||
throw new BadRequestException("L'account di questa copia è stato rimosso: non c'è niente da copiare di nuovo.");
|
||||
}
|
||||
|
||||
// The file the library has now: the one that took the place of the copied one, else the copied one itself.
|
||||
var sha = copy.SupersededBySha256 ?? copy.SourceSha256;
|
||||
// The file the library has now: the one that took the place of the copied one, else the copied one itself
|
||||
// (it can be back in the library in another entry while the one that replaced it went).
|
||||
string? sha = null;
|
||||
List<MediaLocation> present = [];
|
||||
foreach (var candidate in new[] { copy.SupersededBySha256, copy.SourceSha256 }.OfType<string>().Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
present = (await storage.Media.FindBySha256Async(candidate, ct).ConfigureAwait(false))
|
||||
.Where(l => l.Entry.AccountId == accountId && EntryStateRules.IsPresent(l.Media.State))
|
||||
.ToList();
|
||||
if (present.Count > 0)
|
||||
{
|
||||
sha = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (sha is null)
|
||||
{
|
||||
throw new BadRequestException("Il file non è più in libreria: non c'è niente da copiare di nuovo.");
|
||||
}
|
||||
|
||||
if ((await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false)).Any(c =>
|
||||
c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == accountId && c.DestinationId == copy.DestinationId && c.Variant == copy.Variant))
|
||||
{
|
||||
@@ -264,12 +284,7 @@ public static class ExportApi
|
||||
// Among the files of the account with that content, one that is on the disk: the same SHA-256 can sit in two
|
||||
// entries, and the first one found may be a file the library lost (it would end «non presente in libreria»).
|
||||
var account = await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false);
|
||||
var present = (await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false))
|
||||
.Where(l => l.Entry.AccountId == accountId && EntryStateRules.IsPresent(l.Media.State))
|
||||
.ToList();
|
||||
var location = present.FirstOrDefault(l => account is not null && files.Resolve(account, l.Media) is not null)
|
||||
?? present.FirstOrDefault()
|
||||
?? throw new BadRequestException("Il file non è più in libreria: non c'è niente da copiare di nuovo.");
|
||||
var location = present.FirstOrDefault(l => account is not null && files.Resolve(account, l.Media) is not null) ?? present[0];
|
||||
var service = await hub.GetAsync(ct).ConfigureAwait(false);
|
||||
var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true), ct)).ConfigureAwait(false);
|
||||
return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto);
|
||||
@@ -531,7 +546,8 @@ public static class ExportApi
|
||||
plan.RemovedOrSuperseded,
|
||||
plan.NotExported,
|
||||
plan.Missing,
|
||||
[.. plan.Destinations.Select(d => new ExportPlanDestinationDto(d.DestinationId, d.Label, Display(root, d.RootPath), Scope(d.Scope), d.Username, d.Files, d.Bytes, d.Paused, d.Problem, d.FreeBytes))]);
|
||||
[.. plan.Destinations.Select(d => new ExportPlanDestinationDto(d.DestinationId, d.Label, Display(root, d.RootPath), Scope(d.Scope), d.Username, d.Files, d.Bytes, d.Paused, d.Problem, d.FreeBytes))],
|
||||
plan.HasDestination);
|
||||
}
|
||||
|
||||
/// <summary>The request of a «Copia in…»: exactly one selection.</summary>
|
||||
|
||||
@@ -132,7 +132,8 @@ public sealed record ExportPlanDto(
|
||||
int RemovedOrSuperseded,
|
||||
int NotExported,
|
||||
int Missing,
|
||||
IReadOnlyList<ExportPlanDestinationDto> Destinations);
|
||||
IReadOnlyList<ExportPlanDestinationDto> Destinations,
|
||||
bool HasDestination = true);
|
||||
|
||||
/// <summary>The jobs a «Copia in…» started, one per destination (empty: nothing to copy), and the plan it followed.</summary>
|
||||
public sealed record ExportJobDto(IReadOnlyList<long> RunIds, ExportPlanDto Plan, string Message);
|
||||
|
||||
@@ -387,10 +387,11 @@ public static class LibraryApi
|
||||
continue;
|
||||
}
|
||||
|
||||
// The copies made for this account; with «Una copia sola», also the ones made for another account in a
|
||||
// folder still in use (that is why this file is «Già copiato»).
|
||||
// The copies made for this account; with «Una copia sola», also the ones made for another account still
|
||||
// in Febe in a folder still in use (that is why this file is «Già copiato»; a copy whose account was
|
||||
// removed does not count, as in the plan).
|
||||
var own = copy.AccountId == Account.Id;
|
||||
if (!own && !(SamePost == SamePostCopies.OneOnly && copy.State == ExportCopyState.Copied && !destination.IsRetired))
|
||||
if (!own && !(SamePost == SamePostCopies.OneOnly && copy.AccountId is not null && copy.State == ExportCopyState.Copied && !destination.IsRetired))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,9 @@ export async function mountExport(page) {
|
||||
let timer = 0;
|
||||
let ticks = 0;
|
||||
let stopped = false;
|
||||
// One reading at a time: a command or a change during a reading asks for one more right after it, never a second chain.
|
||||
let inFlight = false;
|
||||
let rerun = false;
|
||||
page.onLeave(() => {
|
||||
stopped = true;
|
||||
clearTimeout(timer);
|
||||
@@ -53,6 +56,29 @@ export async function mountExport(page) {
|
||||
|
||||
async function poll() {
|
||||
if (stopped) return;
|
||||
if (inFlight) {
|
||||
rerun = true;
|
||||
return;
|
||||
}
|
||||
inFlight = true;
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
await read();
|
||||
} finally {
|
||||
inFlight = false;
|
||||
}
|
||||
if (stopped) return;
|
||||
clearTimeout(timer);
|
||||
if (rerun) {
|
||||
rerun = false;
|
||||
wasRunning = null;
|
||||
poll();
|
||||
return;
|
||||
}
|
||||
timer = setTimeout(poll, progress && progress.running ? 1000 : 5000);
|
||||
}
|
||||
|
||||
async function read() {
|
||||
try {
|
||||
progress = await api('/api/export/progress', { signal: page.signal });
|
||||
} catch (error) {
|
||||
@@ -65,8 +91,6 @@ export async function mountExport(page) {
|
||||
// The jobs and the folders follow the copy: when it starts or ends, and every few seconds while it works.
|
||||
if (running !== wasRunning || !running || ticks % 5 === 0) await loadSide();
|
||||
wasRunning = running;
|
||||
if (stopped) return;
|
||||
timer = setTimeout(poll, running ? 1000 : 5000);
|
||||
}
|
||||
|
||||
/** Asks again now (after a command), keeping one timer. */
|
||||
|
||||
@@ -165,7 +165,10 @@ export async function destinationDialog({ scope, accountId = null, username = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function browse(path) {
|
||||
// focusPath: the folder whose button had the keyboard; after the list is drawn again the focus goes back there
|
||||
// (or to the first folder), never lost on the page behind the dialog.
|
||||
async function browse(path, focusPath = null) {
|
||||
const hadFocus = folderPart.contains(document.activeElement);
|
||||
try {
|
||||
const list = await api(`/api/export/folders${path ? `?path=${encodeURIComponent(path)}` : ''}`);
|
||||
fill(folderPart, h('div.pannello.sfoglia',
|
||||
@@ -173,10 +176,16 @@ export async function destinationDialog({ scope, accountId = null, username = ''
|
||||
list.parent != null ? h('button.btn.nudo.piccolo.destra', { type: 'button', onclick: () => browse(list.parent || null) }, icon('arrow-left', 's'), t('esportazione.dialogo.su')) : null),
|
||||
list.folders.length
|
||||
? h('ul.sfoglia-elenco', list.folders.map((f) => h(`li${f.path === state.path ? '.scelta' : ''}`,
|
||||
h('button.sfoglia-voce', { type: 'button', 'aria-pressed': String(f.path === state.path), onclick: () => { state.path = f.path; checkFolder(f.path); browse(list.relative || null); } },
|
||||
h('button.sfoglia-voce', { type: 'button', dataset: { path: f.path }, 'aria-pressed': String(f.path === state.path), onclick: () => { state.path = f.path; checkFolder(f.path); browse(list.relative || null, f.path); } },
|
||||
icon(f.path === state.path ? 'circle-check' : 'folder', 's'), h('span', f.name)),
|
||||
f.hasSubfolders ? h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('esportazione.dialogo.apri', { nome: f.name }), onclick: () => browse(f.path) }, icon('chevron-right', 's')) : null)))
|
||||
: h('p.vuoto-elenco', t('esportazione.dialogo.vuota'))));
|
||||
if (hadFocus) {
|
||||
const items = [...folderPart.querySelectorAll('.sfoglia-voce')];
|
||||
const target = items.find((b) => focusPath != null && b.dataset.path === focusPath) || items[0]
|
||||
|| folderPart.querySelector('button');
|
||||
if (target) target.focus();
|
||||
}
|
||||
} catch (error) {
|
||||
fill(folderPart, h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', error.message)));
|
||||
}
|
||||
@@ -409,6 +418,10 @@ export function copyDialog(selection, { title } = {}) {
|
||||
let plan = null;
|
||||
let token = 0;
|
||||
let busy = false;
|
||||
// The files «tolti o superati» as the plan without «Copia di nuovo» counts them: the choice keeps its label and
|
||||
// stays on screen whatever the plan with it says (with it they are files to copy).
|
||||
let againCount = 0;
|
||||
let refocusAgain = false;
|
||||
|
||||
async function load() {
|
||||
const mine = ++token;
|
||||
@@ -417,6 +430,7 @@ export function copyDialog(selection, { title } = {}) {
|
||||
const result = await api('/api/export/plan', { method: 'POST', body: { ...selection, copyAgain } });
|
||||
if (mine !== token) return;
|
||||
plan = result;
|
||||
if (!copyAgain) againCount = result.removedOrSuperseded || 0;
|
||||
draw();
|
||||
} catch (error) {
|
||||
if (mine !== token) return;
|
||||
@@ -446,16 +460,26 @@ export function copyDialog(selection, { title } = {}) {
|
||||
d.problem || d.paused ? h('div.avviso.ambra', icon('pause', 's'), h('span', t('esportazione.copia.inAttesa', { problema: d.problem || t('esportazione.inPausa') }))) : null)));
|
||||
let empty = null;
|
||||
if (!p.files) {
|
||||
empty = p.destinations.length === 0 && p.notExported && !p.alreadyCopied && !p.removedOrSuperseded
|
||||
? h('p.aiuto', t('esportazione.copia.nessunaCartella'))
|
||||
: h('p.aiuto', t('esportazione.copia.niente'));
|
||||
// «Nessuna cartella» only when there is really none; files of accounts not exported (or of kinds the folder
|
||||
// does not copy) have their own words.
|
||||
let key = 'esportazione.copia.niente';
|
||||
if (p.hasDestination === false) key = 'esportazione.copia.nessunaCartella';
|
||||
else if (p.notExported && !p.alreadyCopied && !p.removedOrSuperseded) key = 'esportazione.copia.nienteNonEsportati';
|
||||
empty = h('p.aiuto', t(key));
|
||||
}
|
||||
const again = p.removedOrSuperseded
|
||||
? h('div.di-nuovo',
|
||||
checkbox({ checked: copyAgain, label: t('esportazione.copia.diNuovo', { n: p.removedOrSuperseded }), onchange: (v) => { copyAgain = v; load(); } }),
|
||||
h('p.aiuto', t('esportazione.copia.diNuovoAiuto')))
|
||||
const choice = againCount || copyAgain
|
||||
? checkbox({
|
||||
checked: copyAgain,
|
||||
label: t('esportazione.copia.diNuovo', { n: againCount || p.removedOrSuperseded }),
|
||||
onchange: (v) => { copyAgain = v; refocusAgain = true; load(); },
|
||||
})
|
||||
: null;
|
||||
const again = choice
|
||||
? h('div.di-nuovo', choice, h('p.aiuto', t('esportazione.copia.diNuovoAiuto')))
|
||||
: null;
|
||||
fill(content, summary, rows.length ? h('ul.destinazioni-copia.pannello', rows) : null, empty, again);
|
||||
if (refocusAgain && choice) choice.input.focus();
|
||||
refocusAgain = false;
|
||||
fill(start, icon('copy'), t('esportazione.copia.pulsante', { n: p.files }));
|
||||
start.disabled = busy || !p.files;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
|
||||
import { api, withCarried } from '../core/api.js';
|
||||
import { caps, serverNow } from '../core/context.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { h, icon, fill, later } from '../core/dom.js';
|
||||
import { onLibrary } from '../core/engine.js';
|
||||
import { t, dayName, capitalize, bytes, duration, number, ago, shortDay } from '../core/text.js';
|
||||
import { avatar, label, showError, toast } from '../core/ui.js';
|
||||
import { confirmDelete } from './library.js';
|
||||
@@ -26,6 +27,8 @@ export function openViewer({ tile, source, origin, onDeleted }) {
|
||||
let fileIndex = 0;
|
||||
let zoomed = false;
|
||||
let token = 0;
|
||||
// The copies whose «Copia di nuovo» started a job: their button stays «In copia…» until the job ends (spec §4.10).
|
||||
const copying = new Set();
|
||||
|
||||
const where = h('span.dove');
|
||||
const closeButton = h('button.tondino', { type: 'button', 'aria-label': t('vis.chiudi'), title: t('vis.chiudi'), onclick: close }, icon('x'));
|
||||
@@ -77,6 +80,8 @@ export function openViewer({ tile, source, origin, onDeleted }) {
|
||||
|
||||
function close() {
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
stopWatching();
|
||||
onCopiesChanged.cancel();
|
||||
for (const v of box.querySelectorAll('video')) v.pause();
|
||||
if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
|
||||
box.remove();
|
||||
@@ -286,17 +291,24 @@ export function openViewer({ tile, source, origin, onDeleted }) {
|
||||
const vars = { cartella: copy.destination, giorno: shortDay(copy.at.day, today), nome: copy.forAccount || '' };
|
||||
const key = { copied: copy.forAccount ? 'copiatoPer' : 'copiato', removed: 'tolto', superseded: 'superato' }[copy.state] || 'fallito';
|
||||
const text = t(`esportazione.vis.${key}`, vars) + (copy.destinationRetired ? ` (${t('esportazione.vis.tolta')})` : '');
|
||||
const busy = copying.has(copy.copyId);
|
||||
const again = copy.canCopyAgain
|
||||
? h('button.btn.nudo.piccolo.copia-di-nuovo', {
|
||||
type: 'button',
|
||||
disabled: busy,
|
||||
onclick: async (e) => {
|
||||
const button = e.currentTarget;
|
||||
button.disabled = true;
|
||||
const job = await copyAgain(copy.copyId);
|
||||
if (job) await load(entry.id, fileIndex, media.id);
|
||||
else button.disabled = false;
|
||||
if (!job) {
|
||||
button.disabled = false;
|
||||
return;
|
||||
}
|
||||
// The job runs on: the row says so, and the viewer reads the copies again when it ends (onLibrary «export»).
|
||||
copying.add(copy.copyId);
|
||||
await load(entry.id, fileIndex, media.id);
|
||||
},
|
||||
}, icon('rotate-cw', 's'), t('esportazione.vis.diNuovo'))
|
||||
}, icon('rotate-cw', 's'), t(busy ? 'esportazione.vis.inCopia' : 'esportazione.vis.diNuovo'))
|
||||
: null;
|
||||
return [h('dt', t('esportazione.vis.copia')), h('dd.riga-copia', h('span', text), again)];
|
||||
}
|
||||
@@ -331,6 +343,17 @@ export function openViewer({ tile, source, origin, onDeleted }) {
|
||||
else close();
|
||||
}
|
||||
|
||||
// A job of the copies ended (or a folder changed): the rows of «Copia» are read again, on the same file.
|
||||
const onCopiesChanged = later(() => {
|
||||
if (!entry) return;
|
||||
copying.clear();
|
||||
const current = entry.media[fileIndex];
|
||||
load(entry.id, fileIndex, current ? current.id : null);
|
||||
}, 400);
|
||||
const stopWatching = onLibrary((change) => {
|
||||
if (change.reason === 'export') onCopiesChanged();
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
document.body.append(box);
|
||||
closeButton.focus();
|
||||
|
||||
@@ -1183,6 +1183,7 @@
|
||||
"diNuovoAiuto": "Scrive un file nuovo; la copia di prima resta dov'è.",
|
||||
"niente": "Niente da copiare: i file scelti sono già copiati, non si esportano o non sono in libreria.",
|
||||
"nessunaCartella": "Nessuna cartella delle copie: scegline una in Impostazioni → Esportazione.",
|
||||
"nienteNonEsportati": "Niente da copiare: questi file sono di account che non si esportano o di tipi che la cartella non copia.",
|
||||
"pulsante": "Copia 1 file|Copia {n} file",
|
||||
"vediAvanzamento": "Apri l'esportazione"
|
||||
},
|
||||
@@ -1206,6 +1207,7 @@
|
||||
"fallito": "Non riuscito in {cartella} il {giorno}",
|
||||
"tolta": "cartella tolta",
|
||||
"diNuovo": "Copia di nuovo",
|
||||
"inCopia": "In copia…",
|
||||
"copiaIn": "Copia in…"
|
||||
},
|
||||
"account": {
|
||||
|
||||
Reference in new issue
Block a user