using System.Security.Cryptography; using Febe.Core.Domain; using Febe.Core.Library; namespace Febe.Core.Import; /// What the content of one file says, measured without changing anything. internal sealed record ContentFacts( DetectedType? Type, long Bytes, string? Sha256, int? Width, int? Height, TimeSpan? Duration, ulong? PerceptualHash, DateTimeOffset? MetadataDate, string? Error); /// /// Reads one source file, read-only (spec §9.2): type from the content, size, SHA-256, dimensions, perceptual hash for /// photos, date from the metadata (EXIF for photos, mvhd for MP4/MOV, ffprobe as an extra for the rest). /// internal static class ContentAnalysis { /// Photos up to this size are read once into memory (hash, EXIF and decoding from the same bytes). private const long InMemoryLimit = 64L * 1024 * 1024; public static async Task AnalyzeAsync(string fullPath, ImportEnvironment env, CancellationToken ct) { try { var length = new FileInfo(fullPath).Length; var head = new byte[Math.Min(length, ExifDateReader.HeadLength)]; await using (var stream = env.FileSystem.OpenRead(fullPath)) { await stream.ReadExactlyAsync(head, ct).ConfigureAwait(false); } var type = MediaSniffer.Detect(head, Path.GetExtension(fullPath)); if (type is null || length == 0) { return new ContentFacts(null, length, null, null, null, null, null, null, null); } return type.Kind == MediaKind.Photo ? await PhotoAsync(fullPath, type, length, head, env, ct).ConfigureAwait(false) : await VideoAsync(fullPath, type, length, env, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return new ContentFacts(null, 0, null, null, null, null, null, null, $"Il file non si è potuto leggere ({ex.GetType().Name})."); } } private static async Task PhotoAsync(string fullPath, DetectedType type, long length, byte[] head, ImportEnvironment env, CancellationToken ct) { string sha; int? width = null, height = null; ulong? hash = null; if (length <= InMemoryLimit) { var bytes = new byte[length]; await using (var stream = env.FileSystem.OpenRead(fullPath)) { await stream.ReadExactlyAsync(bytes, ct).ConfigureAwait(false); } sha = Convert.ToHexStringLower(SHA256.HashData(bytes)); ct.ThrowIfCancellationRequested(); (width, height, hash) = Decode(() => new MemoryStream(bytes, writable: false)); } else { sha = await env.FileSystem.ComputeSha256Async(fullPath, ct).ConfigureAwait(false); ct.ThrowIfCancellationRequested(); (width, height, hash) = Decode(() => env.FileSystem.OpenRead(fullPath)); } var date = ExifDateReader.Read(head, env.Clock.LocalZone); return new ContentFacts(type, length, sha, width, height, null, hash, date, null); } private static (int? Width, int? Height, ulong? Hash) Decode(Func open) { try { int? width = null, height = null; using (var stream = open()) { if (ImageDecoding.ReadSize(stream) is { } size) { (width, height) = size; } } using var again = open(); return (width, height, PerceptualHash.Compute(again)); } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OutOfMemoryException) { return (null, null, null); // a format SkiaSharp cannot decode (e.g. HEIC): no size, no hash } } private static async Task VideoAsync(string fullPath, DetectedType type, long length, ImportEnvironment env, CancellationToken ct) { var sha = await env.FileSystem.ComputeSha256Async(fullPath, ct).ConfigureAwait(false); DateTimeOffset? created = null; TimeSpan? duration = null; int? width = null, height = null; if (type.IsIsoMedia) { try { if (Mp4Reader.ReadFile(fullPath, env.Clock.Now) is { } info) { (created, duration, width, height) = (info.CreatedAt, info.Duration, info.Width, info.Height); } } catch (Exception ex) when (ex is IOException or ArgumentException or EndOfStreamException) { // A damaged header: the date comes from elsewhere. } } if (env.VideoProbe is { } probe && (created is null || duration is null || width is null)) { var extra = await probe.ProbeAsync(fullPath, ct).ConfigureAwait(false); if (extra is not null) { created ??= extra.CreatedAt is { } c && c <= env.Clock.Now.AddDays(1) ? c : null; duration ??= extra.Duration; width ??= extra.Width; height ??= extra.Height; } } return new ContentFacts(type, length, sha, width, height, duration, null, created, null); } }