Lettori ISO BMFF (anche frammentato), Matroska/WebM e AVI; ContainerVideoMetadataProbe è la sonda predefinita; VideoFrameDecoder (H.264 in casa, BMP ruotato, riconoscimento dei video fermi) sostituisce VideoFrameExtractor; Mp4Writer con moov in testa. Tolti ffmpeg e ffprobe da Dockerfile, CI, script e prove. WIP perché la corsa completa di tests/Febe.Tests non era finita al momento del commit e l'ultima correzione (data qualsiasi nella lettura dei campioni) non è stata ricompilata né riprovata: la compilazione durante la corsa fallisce per DLL bloccate dalle prove in esecuzione. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
235 lines
8.4 KiB
C#
235 lines
8.4 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. It never moves, renames or deletes a file (rule 12).
|
|
/// </summary>
|
|
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 };
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>Starts the rebuild; false when one is already running.</summary>
|
|
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;
|
|
}
|
|
}
|
|
|
|
/// <summary>Waits for the running rebuild (tests).</summary>
|
|
public Task WaitAsync() => _task ?? Task.CompletedTask;
|
|
|
|
private async Task RunAsync()
|
|
{
|
|
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"));
|
|
}
|
|
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>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);
|
|
}
|