using System.Security.Cryptography;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
using Febe.Core.Storage;
namespace Febe.Core.Export;
///
/// What the export needs from the rest of Febe (spec §4.10). Built once by the composition (the web layer's export
/// hub); the layout is a function because on Windows the library folder can change while Febe runs.
///
public sealed record ExportEnvironment
{
public required IFebeStorage Storage { get; init; }
/// The library folder and account folders now.
public required Func Layout { get; init; }
/// The Data folder: a destination may not overlap it.
public required string DataFolder { get; init; }
public required IClock Clock { get; init; }
/// Docker /importa: a destination may not overlap it. Null on Windows.
public string? ImportRoot { get; init; }
/// Where destinations may be chosen (Docker: /esporta).
public ExportRootOptions Root { get; init; } = ExportRootOptions.AnyFolder;
///
/// The full path of a library file present on disk, or null. Null: the library layout (as the web layer's
/// LibraryFileResolver). Use .
///
public Func? ResolveSource { get; init; }
/// Reading and hashing files (library files and files found in a destination).
public IExportFileSystem FileSystem { get; init; } = ExportFileSystem.Instance;
/// Free space and the FAT32 limit of a destination.
public IExportDisk Disk { get; init; } = new SystemExportDisk(new ProcMountInfo());
/// Copies never run during an engine session.
public IEngineSessionState Session { get; init; } = NoEngineSession.Instance;
/// Shared with import and rebuild: never together (spec §4.10). Null: nothing else to keep out (tests).
public LongWorkGate? Gate { get; init; }
/// Time allowed to a check of a destination folder (a disconnected share must not block).
public TimeSpan FolderCheckTimeout { get; init; } = TimeSpan.FromSeconds(10);
/// Writes the probe file of a folder check (a seam: tests make it fail or hang); null: the real file.
public Action? WriteProbe { get; init; }
/// How often a waiting job looks whether the engine session ended.
public TimeSpan SessionPoll { get; init; } = TimeSpan.FromSeconds(5);
/// A group of copies, checked with a probe before it starts: at most this many files…
public int GroupFiles { get; init; } = 100;
/// …or this many planned bytes, whichever comes first.
public long GroupBytes { get; init; } = 1L << 30;
/// One conversion at a time in the process (tappa E3, D16): shared with the library conversion.
public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared;
/// The checker of destination folders of this environment.
public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout, WriteProbe);
/// The protected folders now (Data, library, account folders, /importa) and the extra ones.
public Task FolderContextAsync(IReadOnlyList? extra, CancellationToken ct) =>
ExportFolderCheck.ContextAsync(Storage, Layout(), DataFolder, ImportRoot, Root, extra, ct);
/// The full path of a library file present on disk, or null ( or the layout).
public string? ResolveSourcePath(Account account, Media media)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(media);
if (ResolveSource is { } resolve)
{
return resolve(account, media);
}
if (media.RelativePath is null || !EntryStateRules.IsPresent(media.State))
{
return null;
}
try
{
var path = Layout().FullPath(account, media.RelativePath);
return FileSystem.FileExists(path) ? path : null;
}
catch (ArgumentException)
{
return null;
}
}
}
/// File operations of the export (a seam, like IImportFileSystem).
public interface IExportFileSystem
{
/// Opens a file for reading only.
Stream OpenRead(string path);
///
/// Opens a file for reading at any position (a video to remux or to take frames from, tappa E3). By default the
/// stream of , which can seek.
///
Stream OpenRandomAccess(string path) => OpenRead(path);
/// SHA-256 (lowercase hex) of a file as it is on disk now.
Task ComputeSha256Async(string path, CancellationToken ct);
bool FileExists(string path);
/// Size of a file, or null when it is not there.
long? FileLength(string path);
}
/// The real file system.
public sealed class ExportFileSystem : IExportFileSystem
{
private const int BufferSize = 128 * 1024;
private ExportFileSystem()
{
}
public static ExportFileSystem Instance { get; } = new();
// FileShare.Delete: a long read never blocks «Elimina dalla libreria» on Windows (tappa E3).
public Stream OpenRead(string path) =>
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
/// As ContainerReader.OpenRead: shared for reading, writing and deleting, read at random positions.
public Stream OpenRandomAccess(string path) =>
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, BufferSize, FileOptions.RandomAccess);
public async Task ComputeSha256Async(string path, CancellationToken ct)
{
await using var stream = OpenRead(path);
return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
}
public bool FileExists(string path) => File.Exists(path);
public long? FileLength(string path)
{
try
{
var info = new FileInfo(path);
return info.Exists ? info.Length : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
return null;
}
}
}