Le copie esterne diventano usabili dall'interfaccia: ExportHub costruisce l'unico ExportService del web (segna «interrotto» ciò che l'arresto ha fermato e avvisa le pagine a lavoro finito), ExportApi espone cartelle, scelta e controllo della cartella, «Copia in…» (piano e avvio), «Copia di nuovo», avanzamento, lavori, ripresa, annullamento e resoconto. Gli endpoint esistenti portano le copie: filtro copies= della Libreria, segno «Copiato» / «Copiato in parte 1/3» sulle tessere, copie di ogni file nel visualizzatore, riquadro «Copie esterne» e interruttore «Esporta questo account» nella scheda. Una cartella di account o della libreria che finirebbe dentro (o attorno a) una cartella delle copie è rifiutata; dopo una ricostruzione le cartelle in conflitto vanno in pausa. Composizione: in Docker le copie si scrivono solo sotto /esporta, e solo con --esporta/FEBE_ESPORTA e un montaggio (riga di avvio e avviso se manca); sul desktop qualsiasi cartella con la finestra del sistema e lo spazio libero misurato anche sulle condivisioni di rete. La dimostrazione ha una cartella generale, una propria, un account non esportato e copie vere in ogni stato, scritte dal motore nella sua cartella temporanea. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
273 lines
10 KiB
C#
273 lines
10 KiB
C#
using System.Collections.Concurrent;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Library;
|
|
using Febe.Core.Storage;
|
|
|
|
namespace Febe.Web.Library;
|
|
|
|
/// <summary>
|
|
/// «Cambia…» of the Data folder (Impostazioni, Generali; spec §4.7, §8.2). The Data folder holds the database and the
|
|
/// browser profile with the Instagram session: it cannot move while Febe runs, so the shell records the choice and uses
|
|
/// it at the next start. The desktop implements it (M6); Docker changes it from the container (read-only here).
|
|
/// </summary>
|
|
public interface IDataFolderChange
|
|
{
|
|
/// <summary>The shell can record a new Data folder.</summary>
|
|
bool CanChange { get; }
|
|
|
|
/// <summary>Records the new folder for the next start; returns the Italian message for the page.</summary>
|
|
Task<string> RequestChangeAsync(string newFolder, CancellationToken ct);
|
|
}
|
|
|
|
/// <summary>Default: the Data folder is fixed by the composition (Docker volume, command line).</summary>
|
|
public sealed class FixedDataFolder : IDataFolderChange
|
|
{
|
|
public bool CanChange => false;
|
|
|
|
public Task<string> RequestChangeAsync(string newFolder, CancellationToken ct) =>
|
|
throw new Api.BadRequestException("La cartella dei dati qui non si cambia dall'interfaccia: si sceglie quando si avvia Febe (in Docker, con il volume /dati).");
|
|
}
|
|
|
|
/// <summary>Setting keys of the desktop shell, edited from the interface.</summary>
|
|
public static class DesktopSettingKeys
|
|
{
|
|
/// <summary>«Chiudendo la finestra, Febe resta attivo nell'area di notifica» (true/false, default true). Read by the desktop (M6).</summary>
|
|
public const string KeepInTray = "desktop.resta-nell-area-di-notifica";
|
|
}
|
|
|
|
/// <summary>Sizes of folders, measured in the background and kept for a while (a big thumbnails folder takes seconds).</summary>
|
|
public sealed class FolderSizes(IClock clock)
|
|
{
|
|
/// <summary>How long a measure stays good.</summary>
|
|
public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(10);
|
|
|
|
private readonly ConcurrentDictionary<string, Measure> _measures = new(StringComparer.Ordinal);
|
|
|
|
/// <summary>The last known size of a folder (null while the first measure runs); starts a new measure when stale.</summary>
|
|
public (long? Bytes, bool Measuring) Get(string folder)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
|
|
var now = clock.Now;
|
|
var measure = _measures.GetOrAdd(folder, _ => new Measure());
|
|
lock (measure)
|
|
{
|
|
if (!measure.Running && (measure.Bytes is null || now - measure.At > Lifetime))
|
|
{
|
|
measure.Running = true;
|
|
_ = Task.Run(() =>
|
|
{
|
|
var bytes = SizeOf(folder);
|
|
lock (measure)
|
|
{
|
|
measure.Bytes = bytes;
|
|
measure.At = clock.Now;
|
|
measure.Running = false;
|
|
}
|
|
});
|
|
}
|
|
|
|
return (measure.Bytes, measure.Running);
|
|
}
|
|
}
|
|
|
|
/// <summary>Forgets a measure (after a backup or a rebuild).</summary>
|
|
public void Invalidate(string folder) => _measures.TryRemove(folder, out _);
|
|
|
|
/// <summary>Total size of the files below a folder; unreadable parts are skipped.</summary>
|
|
public static long SizeOf(string folder)
|
|
{
|
|
if (!Directory.Exists(folder))
|
|
{
|
|
return 0;
|
|
}
|
|
|
|
long total = 0;
|
|
try
|
|
{
|
|
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint }))
|
|
{
|
|
try
|
|
{
|
|
total += file.Length;
|
|
}
|
|
catch (IOException)
|
|
{
|
|
// the file went away while counting
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
|
{
|
|
// keep what was counted
|
|
}
|
|
|
|
return total;
|
|
}
|
|
|
|
/// <summary>Free bytes on the disk that holds <paramref name="path"/>; null when unknown.</summary>
|
|
public static long? FreeBytes(string path)
|
|
{
|
|
try
|
|
{
|
|
var full = Path.GetFullPath(path);
|
|
DriveInfo? best = null;
|
|
foreach (var drive in DriveInfo.GetDrives())
|
|
{
|
|
string root;
|
|
try
|
|
{
|
|
root = drive.RootDirectory.FullName;
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (Inside(full, root) && (best is null || root.Length > best.RootDirectory.FullName.Length))
|
|
{
|
|
best = drive;
|
|
}
|
|
}
|
|
|
|
return best is { IsReady: true } ? best.AvailableFreeSpace : null;
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static bool Inside(string path, string root)
|
|
{
|
|
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
|
var r = Path.TrimEndingDirectorySeparator(root);
|
|
return r.Length == 0 || string.Equals(path, r, comparison) || path.StartsWith(r + Path.DirectorySeparatorChar, comparison) || r == "/";
|
|
}
|
|
|
|
private sealed class Measure
|
|
{
|
|
public long? Bytes { get; set; }
|
|
|
|
public DateTimeOffset At { get; set; }
|
|
|
|
public bool Running { get; set; }
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// «Ricostruisci il database dalla libreria» (spec §8.5) as a background job with its progress and its last report,
|
|
/// one at a time, never together with an import or a copy to external folders (the shared <see cref="LongWorkGate"/>,
|
|
/// spec §4.10). It never moves, renames or deletes a file (rule 12).
|
|
/// </summary>
|
|
public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock clock, LibraryChanges changes, LongWorkGate gate, Export.ExportHub? exports = null)
|
|
{
|
|
private readonly Lock _gate = new();
|
|
private Task? _task;
|
|
|
|
public RebuildState State { get; private set; } = RebuildState.Idle;
|
|
|
|
public bool Running
|
|
{
|
|
get
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return _task is { IsCompleted: false };
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>Starts the rebuild; false when one is already running or another long job holds the gate.</summary>
|
|
public bool TryStart() => TryStart(out _);
|
|
|
|
/// <summary>
|
|
/// Starts the rebuild; false, with the Italian reason in <paramref name="busy"/>, when a rebuild, an import or a copy
|
|
/// to external folders is running.
|
|
/// </summary>
|
|
public bool TryStart(out string? busy)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (_task is { IsCompleted: false })
|
|
{
|
|
busy = LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild);
|
|
return false;
|
|
}
|
|
|
|
if (!gate.TryEnter(LongWorkKind.Rebuild, out var lease, out var holder))
|
|
{
|
|
busy = LongWorkGate.BusyMessage(LongWorkKind.Rebuild, holder!.Value);
|
|
return false;
|
|
}
|
|
|
|
busy = null;
|
|
State = RebuildState.Idle with { Running = true, StartedAt = clock.Now };
|
|
_task = Task.Run(() => RunAsync(lease));
|
|
return true;
|
|
}
|
|
}
|
|
|
|
/// <summary>Waits for the running rebuild (tests).</summary>
|
|
public Task WaitAsync() => _task ?? Task.CompletedTask;
|
|
|
|
private async Task RunAsync(IDisposable lease)
|
|
{
|
|
using var held = lease;
|
|
var progress = new SyncProgress<RebuildProgress>(p => State = State with { Folder = p.Folder, FoldersDone = p.FoldersDone, FoldersTotal = p.FoldersTotal, FilesChecked = p.FilesChecked });
|
|
try
|
|
{
|
|
var rebuilder = new LibraryRebuilder(storage, library.Layout, clock, library.Thumbnails, VideoFrameDecoder.Instance, library.HashIndex);
|
|
var report = await rebuilder.RebuildAsync(new RebuildOptions(), progress).ConfigureAwait(false);
|
|
State = State with { Running = false, Report = report, FinishedAt = clock.Now };
|
|
changes.Publish(new LibraryChange(clock.Now, null, "rebuild"));
|
|
await RecheckExportsAsync().ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
|
|
{
|
|
State = State with { Running = false, Error = ex.Message, FinishedAt = clock.Now };
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// After a rebuild the account folders may be others: a destination of the copies that now sits inside one of them,
|
|
/// or around it, is paused with the reason (spec §4.10). A failure here leaves the rebuild done.
|
|
/// </summary>
|
|
private async Task RecheckExportsAsync()
|
|
{
|
|
if (exports is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
await (await exports.GetAsync().ConfigureAwait(false)).Destinations.RecheckAndPauseAsync(CancellationToken.None).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
|
|
{
|
|
// Nothing is lost: every copy checks its destination again before writing (and pauses it).
|
|
}
|
|
}
|
|
|
|
/// <summary>Progress reported on the calling thread (no synchronization context to post to).</summary>
|
|
private sealed class SyncProgress<T>(Action<T> action) : IProgress<T>
|
|
{
|
|
public void Report(T value) => action(value);
|
|
}
|
|
}
|
|
|
|
/// <summary>The state of the rebuild for the page.</summary>
|
|
public sealed record RebuildState(
|
|
bool Running,
|
|
DateTimeOffset? StartedAt,
|
|
string? Folder,
|
|
int FoldersDone,
|
|
int FoldersTotal,
|
|
int FilesChecked,
|
|
RebuildReport? Report,
|
|
string? Error,
|
|
DateTimeOffset? FinishedAt)
|
|
{
|
|
public static RebuildState Idle { get; } = new(false, null, null, 0, 0, 0, null, null, null);
|
|
}
|