using System.Globalization;
using System.Security.Cryptography;
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Import;
///
/// What the import needs from the rest of Febe. Built once by the composition root (Server, Desktop) with the same
/// library objects the collection uses, so thumbnails, hashes and _febe.jsonl lines are made the same way.
///
public sealed record ImportEnvironment
{
public required IFebeStorage Storage { get; init; }
/// Library folder and account folders.
public required LibraryLayout Layout { get; init; }
/// The two naming schemes of the library settings.
public LibraryNaming Naming { get; init; } = LibraryNaming.Default;
public required AccountJournal Journal { get; init; }
public required IClock Clock { get; init; }
public ThumbnailStore? Thumbnails { get; init; }
///
/// The in-memory index of the library's perceptual hashes, shared with the collection. When null the analysis loads
/// its own copy from the database (and imported photos are not added to any shared index).
///
public PerceptualHashIndex? HashIndex { get; init; }
/// ffmpeg, for thumbnails of imported videos (spec §8.4). Null: the neutral tile.
public VideoFrameExtractor? Frames { get; init; }
/// ffprobe, an optional extra for videos the hand-written reader does not cover.
public IVideoMetadataProbe? VideoProbe { get; init; }
/// «Imposta la data del file a quella di pubblicazione» (library setting).
public bool SetFileTimeToPublication { get; init; } = true;
/// Where sources may be chosen (Docker: /importa).
public ImportSourceOptions Sources { get; init; } = ImportSourceOptions.AnyFolder;
/// The Data folder: a source may not overlap it.
public string? DataFolder { get; init; }
/// Read-only detection of sources.
public ISourceAccessProbe? AccessProbe { get; init; }
/// Reading, hashing and deleting source files.
public IImportFileSystem FileSystem { get; init; } = ImportFileSystem.Instance;
/// Files analysed at the same time (hashing and decoding).
public int Parallelism { get; init; } = Math.Clamp(Environment.ProcessorCount, 1, 4);
/// The checker of sources for this environment.
public ImportSources CreateSources() => new(Sources, Layout.Root, DataFolder, AccessProbe);
}
///
/// File operations of the import on the source and on the copies. A separate seam so that the safety rule of «Sposta»
/// (the original goes only after the copy has been verified with SHA-256) can be tested with a corrupted copy.
///
public interface IImportFileSystem
{
/// Opens a source file for reading only.
Stream OpenRead(string fullPath);
/// SHA-256 (lowercase hex) of a file as it is on disk now.
Task ComputeSha256Async(string fullPath, CancellationToken ct);
/// Deletes an original of «Sposta», after its copy was verified.
void DeleteOriginal(string fullPath);
}
/// The real file system.
public sealed class ImportFileSystem : IImportFileSystem
{
private const int BufferSize = 128 * 1024;
private ImportFileSystem()
{
}
public static ImportFileSystem Instance { get; } = new();
public Stream OpenRead(string fullPath) =>
new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
public async Task ComputeSha256Async(string fullPath, CancellationToken ct)
{
await using var stream = OpenRead(fullPath);
return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
}
public void DeleteOriginal(string fullPath) => File.Delete(fullPath);
}
///
/// Choices of an import that have no column in import_run, kept in the setting table under
/// importazione.{id}.*: whether the 4K Stogram hypothesis is on, and the folders that go to a new «Solo archivio»
/// account (created only when the copy starts, so an abandoned import leaves no empty account behind).
///
internal static class ImportRunSettings
{
public static string StogramKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"importazione.{runId}.ipotesi-stogram");
public static string NewAccountsKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"importazione.{runId}.nuovi-account");
public static Task GetStogramAsync(ISettingsStore store, long runId, CancellationToken ct) =>
store.GetBoolAsync(StogramKey(runId), false, ct);
public static Task SetStogramAsync(ISettingsStore store, long runId, bool value, CancellationToken ct) =>
store.SetAsync(StogramKey(runId), value ? "true" : null, ct);
/// Folder → user name of the new «Solo archivio» account it goes to.
public static async Task> GetNewAccountsAsync(ISettingsStore store, long runId, CancellationToken ct)
{
var text = await store.GetAsync(NewAccountsKey(runId), ct).ConfigureAwait(false);
var result = new Dictionary(StringComparer.Ordinal);
if (string.IsNullOrWhiteSpace(text))
{
return result;
}
try
{
if (JsonNode.Parse(text) is JsonObject json)
{
foreach (var (folder, value) in json)
{
if (value?.GetValue() is { Length: > 0 } username)
{
result[folder] = username;
}
}
}
}
catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidOperationException or FormatException)
{
// An unreadable value: as if no new account had been chosen.
}
return result;
}
public static Task SetNewAccountsAsync(ISettingsStore store, long runId, IReadOnlyDictionary folders, CancellationToken ct)
{
if (folders.Count == 0)
{
return store.SetAsync(NewAccountsKey(runId), null, ct);
}
var json = new JsonObject();
foreach (var (folder, username) in folders.OrderBy(f => f.Key, StringComparer.Ordinal))
{
json[folder] = username;
}
return store.SetAsync(NewAccountsKey(runId), json.ToJsonString(), ct);
}
public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) =>
store.SetManyAsync(new Dictionary { [StogramKey(runId)] = null, [NewAccountsKey(runId)] = null }, ct);
}