using System.Collections.Concurrent;
using Febe.Core.Abstractions;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Web.Library;
///
/// «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).
///
public interface IDataFolderChange
{
/// The shell can record a new Data folder.
bool CanChange { get; }
/// Records the new folder for the next start; returns the Italian message for the page.
Task RequestChangeAsync(string newFolder, CancellationToken ct);
}
/// Default: the Data folder is fixed by the composition (Docker volume, command line).
public sealed class FixedDataFolder : IDataFolderChange
{
public bool CanChange => false;
public Task 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).");
}
/// Setting keys of the desktop shell, edited from the interface.
public static class DesktopSettingKeys
{
/// «Chiudendo la finestra, Febe resta attivo nell'area di notifica» (true/false, default true). Read by the desktop (M6).
public const string KeepInTray = "desktop.resta-nell-area-di-notifica";
}
/// Sizes of folders, measured in the background and kept for a while (a big thumbnails folder takes seconds).
public sealed class FolderSizes(IClock clock)
{
/// How long a measure stays good.
public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(10);
private readonly ConcurrentDictionary _measures = new(StringComparer.Ordinal);
/// The last known size of a folder (null while the first measure runs); starts a new measure when stale.
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);
}
}
/// Forgets a measure (after a backup or a rebuild).
public void Invalidate(string folder) => _measures.TryRemove(folder, out _);
/// Total size of the files below a folder; unreadable parts are skipped.
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;
}
/// Free bytes on the disk that holds ; null when unknown.
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; }
}
}
///
/// «Ricostruisci il database dalla libreria» (spec §8.5) as a background job with its progress and its last report,
/// one at a time. It never moves, renames or deletes a file (rule 12).
///
public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock clock, LibraryChanges changes)
{
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 };
}
}
}
/// Starts the rebuild; false when one is already running.
public bool TryStart()
{
lock (_gate)
{
if (_task is { IsCompleted: false })
{
return false;
}
State = RebuildState.Idle with { Running = true, StartedAt = clock.Now };
_task = Task.Run(RunAsync);
return true;
}
}
/// Waits for the running rebuild (tests).
public Task WaitAsync() => _task ?? Task.CompletedTask;
private async Task RunAsync()
{
var progress = new SyncProgress(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"));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
{
State = State with { Running = false, Error = ex.Message, FinishedAt = clock.Now };
}
}
/// Progress reported on the calling thread (no synchronization context to post to).
private sealed class SyncProgress(Action action) : IProgress
{
public void Report(T value) => action(value);
}
}
/// The state of the rebuild for the page.
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);
}