diff --git a/src/Febe.Core/Domain/Import.cs b/src/Febe.Core/Domain/Import.cs index 95f0b96..4c4d84d 100644 --- a/src/Febe.Core/Domain/Import.cs +++ b/src/Febe.Core/Domain/Import.cs @@ -47,6 +47,13 @@ public enum ImportOutcome /// «Non riconosciuto»: neither a photo nor a video. Ignored and listed. Unrecognized, + + /// + /// Identical (same SHA-256) to another file met earlier in the same source (spec §9.3: «i doppioni si cercano anche + /// dentro la sorgente stessa»). Copied at most once: the copy checks the library again and skips it when its twin + /// is already there. + /// + IdenticalInSource, } /// Alberto's decision for a file of an import. @@ -83,6 +90,9 @@ public enum ImportDateSource FileName, Metadata, ModifiedTime, + + /// The _febe.jsonl of a Febe library used as source: the exact publication time. + Journal, } /// An import (spec §8.3 import_run). @@ -177,5 +187,9 @@ public sealed record ImportFile /// Path of the copy relative to the account folder. public string? DestinationPath { get; init; } + /// + /// Last error or note, in Italian, for the report: why the file failed, was skipped or stays out (e.g. «La cartella + /// non è associata a un account»), or what the copy did (e.g. a replacement chosen by Alberto). + /// public string? LastError { get; init; } } diff --git a/src/Febe.Core/Import/ContentAnalysis.cs b/src/Febe.Core/Import/ContentAnalysis.cs new file mode 100644 index 0000000..d250a4b --- /dev/null +++ b/src/Febe.Core/Import/ContentAnalysis.cs @@ -0,0 +1,140 @@ +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); + } +} diff --git a/src/Febe.Core/Import/ExifDateReader.cs b/src/Febe.Core/Import/ExifDateReader.cs new file mode 100644 index 0000000..12eb775 --- /dev/null +++ b/src/Febe.Core/Import/ExifDateReader.cs @@ -0,0 +1,321 @@ +using System.Buffers.Binary; +using System.Globalization; +using Febe.Core.Domain; + +namespace Febe.Core.Import; + +/// +/// Reads the shooting date of a photo from its EXIF block (spec §3: «la lettura della data di scatto dai metadati di una +/// foto si scrive a mano»). Only the few fields that matter: DateTimeOriginal (0x9003), then CreateDate +/// (0x9004, «DateTimeDigitized»), with OffsetTimeOriginal/OffsetTimeDigitized/OffsetTime when the +/// camera wrote the zone. The modification date of IFD0 (0x0132) is not used: editors rewrite it. +/// +/// Containers: JPEG (APP1 «Exif»), TIFF and raw formats built on it, PNG (eXIf chunk), WebP (EXIF chunk). +/// HEIC keeps its EXIF in an item of the meta box and is not read. Every offset is checked: a damaged block gives +/// no date, never an exception. +/// +/// +public static class ExifDateReader +{ + /// Bytes to read from the start of a file: EXIF blocks sit near the start. + public const int HeadLength = 512 * 1024; + + private const ushort TagExifIfd = 0x8769; + private const ushort TagDateTimeOriginal = 0x9003; + private const ushort TagCreateDate = 0x9004; + private const ushort TagOffsetTime = 0x9010; + private const ushort TagOffsetTimeOriginal = 0x9011; + private const ushort TagOffsetTimeDigitized = 0x9012; + private const int MaxEntries = 512; + + /// + /// The shooting date in the first bytes of a photo; null when there is none. Without a zone in the file, the time + /// is read in (Alberto's: cameras write local time). + /// + public static DateTimeOffset? Read(ReadOnlySpan data, TimeZoneInfo zone) + { + ArgumentNullException.ThrowIfNull(zone); + try + { + var tiff = FindTiff(data); + return tiff.IsEmpty ? null : ReadTiff(tiff, zone); + } + catch (ArgumentOutOfRangeException) + { + return null; // a damaged block: no date + } + } + + /// The TIFF structure holding the EXIF data of a JPEG, TIFF, PNG or WebP; empty when there is none. + internal static ReadOnlySpan FindTiff(ReadOnlySpan data) + { + if (data.Length < 8) + { + return []; + } + + if (data[0] == 0xFF && data[1] == 0xD8) + { + return FindInJpeg(data); + } + + if (data.StartsWith("II*\0"u8) || data.StartsWith("MM\0*"u8)) + { + return data; + } + + if (data[0] == 0x89 && data.Slice(1, 3).SequenceEqual("PNG"u8)) + { + return FindInPng(data); + } + + if (data.Length >= 12 && data.StartsWith("RIFF"u8) && data.Slice(8, 4).SequenceEqual("WEBP"u8)) + { + return FindInWebp(data); + } + + return []; + } + + private static ReadOnlySpan FindInJpeg(ReadOnlySpan data) + { + var offset = 2; + while (offset + 4 <= data.Length) + { + if (data[offset] != 0xFF) + { + return []; + } + + var marker = data[offset + 1]; + if (marker == 0xFF) + { + offset++; // fill byte + continue; + } + + if (marker is 0xD8 or 0x01 or (>= 0xD0 and <= 0xD7)) + { + offset += 2; // markers without length + continue; + } + + if (marker is 0xDA or 0xD9) + { + return []; // start of scan or end of image: no EXIF before the picture data + } + + var length = BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset + 2, 2)); + if (length < 2 || offset + 2 + length > data.Length) + { + return []; + } + + var segment = data.Slice(offset + 4, length - 2); + if (marker == 0xE1 && segment.StartsWith("Exif\0\0"u8)) + { + return segment[6..]; + } + + offset += 2 + length; + } + + return []; + } + + private static ReadOnlySpan FindInPng(ReadOnlySpan data) + { + var offset = 8; + while (offset + 12 <= data.Length) + { + var length = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset, 4)); + var type = data.Slice(offset + 4, 4); + if (length > int.MaxValue || offset + 12 + (long)length > data.Length) + { + return []; + } + + if (type.SequenceEqual("eXIf"u8)) + { + var chunk = data.Slice(offset + 8, (int)length); + return chunk.StartsWith("Exif\0\0"u8) ? chunk[6..] : chunk; + } + + if (type.SequenceEqual("IEND"u8)) + { + return []; + } + + offset += 12 + (int)length; + } + + return []; + } + + private static ReadOnlySpan FindInWebp(ReadOnlySpan data) + { + var offset = 12; + while (offset + 8 <= data.Length) + { + var type = data.Slice(offset, 4); + var length = BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset + 4, 4)); + if (length > int.MaxValue || offset + 8 + (long)length > data.Length) + { + return []; + } + + if (type.SequenceEqual("EXIF"u8)) + { + var chunk = data.Slice(offset + 8, (int)length); + return chunk.StartsWith("Exif\0\0"u8) ? chunk[6..] : chunk; + } + + offset += 8 + (int)length + ((int)length & 1); // chunks are padded to an even size + } + + return []; + } + + private static DateTimeOffset? ReadTiff(ReadOnlySpan tiff, TimeZoneInfo zone) + { + if (tiff.Length < 8) + { + return null; + } + + bool little; + if (tiff.StartsWith("II"u8)) + { + little = true; + } + else if (tiff.StartsWith("MM"u8)) + { + little = false; + } + else + { + return null; + } + + if (U16(tiff, 2, little) != 42) + { + return null; + } + + var ifd0 = U32(tiff, 4, little); + var exifIfd = FindTag(tiff, ifd0, TagExifIfd, little) is { } pointer ? U32(tiff, pointer.ValueOffset, little) : (uint?)null; + + string? original = null, created = null, offsetOriginal = null, offsetCreated = null, offsetAny = null; + if (exifIfd is { } exif) + { + original = AsciiTag(tiff, exif, TagDateTimeOriginal, little); + created = AsciiTag(tiff, exif, TagCreateDate, little); + offsetOriginal = AsciiTag(tiff, exif, TagOffsetTimeOriginal, little); + offsetCreated = AsciiTag(tiff, exif, TagOffsetTimeDigitized, little); + offsetAny = AsciiTag(tiff, exif, TagOffsetTime, little); + } + + return Parse(original, offsetOriginal ?? offsetAny, zone) ?? Parse(created, offsetCreated ?? offsetAny, zone); + } + + /// «2021:05:06 07:08:09» with an optional «+02:00» zone. + internal static DateTimeOffset? Parse(string? value, string? offset, TimeZoneInfo zone) + { + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + + var text = value.Trim().TrimEnd('\0').Trim(); + if (text.Length < 19 + || !DateTime.TryParseExact(text[..19], ["yyyy:MM:dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy:MM:dd'T'HH:mm:ss"], CultureInfo.InvariantCulture, DateTimeStyles.None, out var local) + || local.Year < 1900) + { + return null; + } + + if (TryParseOffset(offset, out var zoneOffset)) + { + return new DateTimeOffset(DateTime.SpecifyKind(local, DateTimeKind.Unspecified), zoneOffset); + } + + return LocalCalendar.FromLocal(local, zone); + } + + /// «+02:00» or «-05:00». + private static bool TryParseOffset(string? text, out TimeSpan offset) + { + offset = default; + if (string.IsNullOrWhiteSpace(text)) + { + return false; + } + + var trimmed = text.Trim().TrimEnd('\0').Trim(); + if (trimmed.Length != 6 || trimmed[0] is not ('+' or '-') + || !TimeSpan.TryParseExact(trimmed[1..], @"hh\:mm", CultureInfo.InvariantCulture, out var span) + || span > TimeSpan.FromHours(14)) + { + return false; + } + + offset = trimmed[0] == '-' ? -span : span; + return true; + } + + private readonly record struct IfdEntry(ushort Tag, ushort Type, uint Count, int ValueOffset); + + private static IfdEntry? FindTag(ReadOnlySpan tiff, uint ifdOffset, ushort tag, bool little) + { + if (ifdOffset < 8 || ifdOffset + 2 > (uint)tiff.Length) + { + return null; + } + + var count = U16(tiff, (int)ifdOffset, little); + if (count > MaxEntries) + { + return null; + } + + for (var i = 0; i < count; i++) + { + var at = (int)ifdOffset + 2 + (i * 12); + if (at + 12 > tiff.Length) + { + return null; + } + + if (U16(tiff, at, little) == tag) + { + return new IfdEntry(tag, U16(tiff, at + 2, little), U32(tiff, at + 4, little), at + 8); + } + } + + return null; + } + + private static string? AsciiTag(ReadOnlySpan tiff, uint ifdOffset, ushort tag, bool little) + { + if (FindTag(tiff, ifdOffset, tag, little) is not { Type: 2 } entry || entry.Count == 0 || entry.Count > 64) + { + return null; + } + + var start = entry.Count <= 4 ? entry.ValueOffset : (int)U32(tiff, entry.ValueOffset, little); + if (start < 0 || start + entry.Count > tiff.Length) + { + return null; + } + + return System.Text.Encoding.ASCII.GetString(tiff.Slice(start, (int)entry.Count)).TrimEnd('\0'); + } + + private static ushort U16(ReadOnlySpan data, int offset, bool little) => little + ? BinaryPrimitives.ReadUInt16LittleEndian(data.Slice(offset, 2)) + : BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset, 2)); + + private static uint U32(ReadOnlySpan data, int offset, bool little) => little + ? BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset, 4)) + : BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset, 4)); +} diff --git a/src/Febe.Core/Import/FileNameDates.cs b/src/Febe.Core/Import/FileNameDates.cs new file mode 100644 index 0000000..3bb8a92 --- /dev/null +++ b/src/Febe.Core/Import/FileNameDates.cs @@ -0,0 +1,98 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using Febe.Core.Domain; + +namespace Febe.Core.Import; + +/// A date found in a file name. +/// The instant (UTC offset applied). +/// Only the day was in the name: the time is noon, local. +public readonly record struct NameDate(DateTimeOffset Instant, bool DayOnly); + +/// +/// Dates written in file names by phones, cameras and common tools (spec §9.2: the date is looked for first in the file +/// name). Times are local (Alberto's zone) unless the name says UTC («_UTC», as Instaloader writes). Digits that belong +/// to a longer number (an Instagram identifier) are never read as a date. +/// +/// 2021-05-06 07.08.09, 2021-05-06_07-08-09, WhatsApp Image 2021-05-06 at 07.08.09; +/// IMG_20210506_070809, VID_20210506_070809, PXL_20210506_070809123, 20210506_070809; +/// only the day: IMG-20210506-WA0001, 2021-05-06. +/// +/// +public static partial class FileNameDates +{ + /// The first plausible date in a file name without extension; null when there is none. + /// The name without extension. + /// Alberto's zone, for local times. + /// Current time: dates after it (by more than a day) are not plausible. + public static NameDate? Find(string stem, TimeZoneInfo zone, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(stem); + ArgumentNullException.ThrowIfNull(zone); + foreach (var pattern in new[] { SeparatedDateTime(), CompactDateTime() }) + { + foreach (Match match in pattern.Matches(stem)) + { + if (Build(match, withTime: true, zone, now) is { } found) + { + return found; + } + } + } + + foreach (var pattern in new[] { SeparatedDate(), CompactDate() }) + { + foreach (Match match in pattern.Matches(stem)) + { + if (Build(match, withTime: false, zone, now) is { } found) + { + return found; + } + } + } + + return null; + } + + private static NameDate? Build(Match match, bool withTime, TimeZoneInfo zone, DateTimeOffset now) + { + int Part(string name) => int.Parse(match.Groups[name].Value, CultureInfo.InvariantCulture); + var year = Part("y"); + var month = Part("mo"); + var day = Part("d"); + if (year < 1990 || month is < 1 or > 12 || day < 1 || day > DateTime.DaysInMonth(year, month)) + { + return null; + } + + int hour = 12, minute = 0, second = 0; + if (withTime) + { + hour = Part("h"); + minute = Part("mi"); + second = Part("s"); + if (hour > 23 || minute > 59 || second > 59) + { + return null; + } + } + + var local = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Unspecified); + var instant = withTime && match.Groups["utc"].Success + ? new DateTimeOffset(local, TimeSpan.Zero) + : LocalCalendar.FromLocal(local, zone); + return instant > now.AddDays(1) ? null : new NameDate(instant, !withTime); + } + + [GeneratedRegex(@"(?(?:19|20)\d{2})-(?\d{2})-(?\d{2})[ _T-]+(?:at[ _]+)?(?\d{2})[.\-:h_](?\d{2})[.\-:m_](?\d{2})(?!\d)(?_UTC)?", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)] + private static partial Regex SeparatedDateTime(); + + [GeneratedRegex(@"(?(?:19|20)\d{2})(?\d{2})(?\d{2})[_\-T ]?(?\d{2})(?\d{2})(?\d{2})(?:\d{1,3})?(?!\d)", RegexOptions.CultureInvariant)] + private static partial Regex CompactDateTime(); + + [GeneratedRegex(@"(?(?:19|20)\d{2})-(?\d{2})-(?\d{2})(?!\d)", RegexOptions.CultureInvariant)] + private static partial Regex SeparatedDate(); + + [GeneratedRegex(@"(?(?:19|20)\d{2})(?\d{2})(?\d{2})(?!\d)", RegexOptions.CultureInvariant)] + private static partial Regex CompactDate(); +} diff --git a/src/Febe.Core/Import/ImportAnalyzer.cs b/src/Febe.Core/Import/ImportAnalyzer.cs new file mode 100644 index 0000000..322f87c --- /dev/null +++ b/src/Febe.Core/Import/ImportAnalyzer.cs @@ -0,0 +1,416 @@ +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Import; + +/// +/// Step 2 of the import (spec §9.2, §9.3): lists the source, reads every file and compares it with the library. +/// +/// Strictly read-only: nothing is copied, moved or written into the source. Interruptible (cancellation) and resumable: +/// the state lives in import_run and import_file, each file gets exactly one outcome, and a resumed +/// analysis continues with the files still «da analizzare» (files that could not be read are tried again). +/// +/// +public sealed class ImportAnalyzer(ImportEnvironment env) +{ + private const int BatchSize = 64; + private const int ListingBatchSize = 500; + + /// Records a new import for a checked source (see ). + public async Task CreateRunAsync(ImportSourceInfo source, ImportAnalysisOptions? options = null, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(source); + options ??= new ImportAnalysisOptions(); + var run = await env.Storage.Imports.CreateRunAsync( + new ImportRun + { + SourcePath = source.FullPath, + SourceReadOnly = source.ReadOnly, + Mode = ImportMode.Copy, + State = ImportRunState.Analyzing, + StartedAt = env.Clock.Now, + }, + ct).ConfigureAwait(false); + if (options.StogramHypothesis) + { + await ImportRunSettings.SetStogramAsync(env.Storage.Settings, run.Id, true, ct).ConfigureAwait(false); + } + + return run; + } + + /// + /// Runs (or resumes) the analysis of an import to the end. On cancellation the import becomes «analisi interrotta» + /// and is thrown; on another error it becomes «analisi interrotta» with the + /// error and the exception is thrown. + /// + /// The import, now waiting for the review. + public async Task AnalyzeAsync(long runId, IProgress? progress = null, CancellationToken ct = default) + { + var run = await env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Importazione {runId} non trovata."); + if (run.State is not (ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted)) + { + throw new InvalidOperationException("L'analisi di questa importazione è già finita."); + } + + run = run with { State = ImportRunState.Analyzing, LastError = null }; + await env.Storage.Imports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false); + try + { + if (!Directory.Exists(run.SourcePath)) + { + throw new ImportSourceException($"La cartella {run.SourcePath} non si trova più: ricollega il disco e riprendi l'analisi."); + } + + var layout = SourceLayout.Inspect(run.SourcePath); + var recognizers = ImportRecognizers.Create( + env.Clock.LocalZone, + () => env.Clock.Now, + await ImportRunSettings.GetStogramAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false)); + await recognizers.PrepareAsync(layout, ct).ConfigureAwait(false); + + await ListAsync(run, layout, progress, ct).ConfigureAwait(false); + await RetryUnreadableAsync(runId, ct).ConfigureAwait(false); + await AnalyzeFilesAsync(run, layout, recognizers, progress, ct).ConfigureAwait(false); + await ApplyDefaultTargetsAsync(run, layout, recognizers, ct).ConfigureAwait(false); + + run = run with { State = ImportRunState.Reviewing, AnalyzedAt = env.Clock.Now, LastError = null }; + await env.Storage.Imports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false); + var summary = await env.Storage.Imports.GetSummaryAsync(runId, CancellationToken.None).ConfigureAwait(false); + await WriteEventAsync( + "importazione-analizzata", + $"Analisi della cartella «{layout.RootName}» finita: {ImportText.Files(summary.Total)}, {ImportText.Count(summary.ByOutcome[ImportOutcome.New], "nuovo", "nuovi")}.", + EventSeverity.Info).ConfigureAwait(false); + progress?.Report(await SnapshotAsync(runId, ImportPhase.Finished, null).ConfigureAwait(false)); + return run; + } + catch (Exception ex) + { + var cancelled = ex is OperationCanceledException && ct.IsCancellationRequested; + run = run with + { + State = ImportRunState.AnalysisInterrupted, + LastError = cancelled ? null : ErrorText(ex), + }; + await env.Storage.Imports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false); + throw; + } + } + + /// A progress snapshot built from the database (also used by the service for an idle import). + public async Task SnapshotAsync(long runId, ImportPhase phase, string? currentFile) + { + var summary = await env.Storage.Imports.GetSummaryAsync(runId, CancellationToken.None).ConfigureAwait(false); + var done = summary.Total - summary.ByState[ImportFileState.Pending]; + long bytesDone = 0; + if (phase is ImportPhase.Analyzing or ImportPhase.Listing) + { + bytesDone = await PendingBytesComplementAsync(runId, summary).ConfigureAwait(false); + } + + var copied = summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved]; + return new ImportProgress(runId, phase, done, summary.Total, bytesDone, summary.Bytes, currentFile, summary.ByOutcome, copied, env.Clock.Now); + } + + private async Task PendingBytesComplementAsync(long runId, ImportSummary summary) + { + long pending = 0; + long after = 0; + while (true) + { + var page = await env.Storage.Imports.ListFilesAsync(new ImportFileQuery { RunId = runId, State = ImportFileState.Pending, AfterId = after, Limit = 10_000 }).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + pending += page.Sum(f => f.Bytes); + after = page[^1].Id; + } + + return summary.Bytes - pending; + } + + /// Lists the source and records the files not known yet, in path order (so «the first met» is stable). + private async Task ListAsync(ImportRun run, SourceLayout layout, IProgress? progress, CancellationToken ct) + { + var known = new HashSet(StringComparer.Ordinal); + long after = 0; + while (true) + { + var page = await env.Storage.Imports.ListFilesAsync(new ImportFileQuery { RunId = run.Id, AfterId = after, Limit = 10_000 }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + foreach (var file in page) + { + known.Add(file.RelativePath); + } + + after = page[^1].Id; + } + + var found = new List(); + var seen = 0; + foreach (var path in Directory.EnumerateFiles(layout.Root, "*", ImportSources.Enumeration(recursive: true))) + { + ct.ThrowIfCancellationRequested(); + if (ImportSources.IsIgnoredFile(Path.GetFileName(path))) + { + continue; + } + + var relative = LibraryLayout.ToStored(Path.GetRelativePath(layout.Root, path)); + if (!known.Contains(relative)) + { + found.Add(relative); + } + + if (++seen % 1000 == 0) + { + progress?.Report(new ImportProgress(run.Id, ImportPhase.Listing, 0, seen, 0, 0, relative, new Dictionary(), 0, env.Clock.Now)); + } + } + + found.Sort(StringComparer.Ordinal); + for (var i = 0; i < found.Count; i += ListingBatchSize) + { + ct.ThrowIfCancellationRequested(); + var batch = new List(); + foreach (var relative in found.Skip(i).Take(ListingBatchSize)) + { + var full = LibraryLayout.FullPath(layout.Root, relative); + var info = new FileInfo(full); + long bytes = 0; + DateTimeOffset? modified = null; + try + { + bytes = info.Length; + modified = new DateTimeOffset(info.LastWriteTimeUtc, TimeSpan.Zero); + } + catch (IOException) + { + // Gone since the listing: the analysis records it as unreadable. + } + + batch.Add(new ImportFile + { + RunId = run.Id, + RelativePath = relative, + Folder = layout.Split(relative).Folder, + Bytes = bytes, + ModifiedAt = modified, + }); + } + + await env.Storage.Imports.AddFilesAsync(batch, ct).ConfigureAwait(false); + } + } + + /// Files that could not be read last time go back to «da analizzare». + private async Task RetryUnreadableAsync(long runId, CancellationToken ct) + { + while (true) + { + var failed = await env.Storage.Imports.ListFilesAsync(new ImportFileQuery { RunId = runId, State = ImportFileState.Failed, Outcome = ImportOutcome.Pending, Limit = 5000 }, ct).ConfigureAwait(false); + if (failed.Count == 0) + { + return; + } + + await env.Storage.Imports.UpdateFilesAsync(failed.Select(f => f with { State = ImportFileState.Pending, LastError = null }).ToList(), ct).ConfigureAwait(false); + } + } + + private async Task AnalyzeFilesAsync(ImportRun run, SourceLayout layout, ImportRecognizers recognizers, IProgress? progress, CancellationToken ct) + { + var comparer = await ImportComparer.CreateAsync( + env.Storage, + env.HashIndex, + run.Id, + file => recognizers.Recognize(new ImportFileContext(layout, file.RelativePath)), + () => env.Clock.Now, + ct).ConfigureAwait(false); + var targets = new Dictionary(StringComparer.Ordinal); + var snapshot = await SnapshotAsync(run.Id, ImportPhase.Analyzing, null).ConfigureAwait(false); + var done = snapshot.FilesDone; + var bytesDone = snapshot.BytesDone; + var outcomes = new Dictionary(snapshot.Outcomes); + progress?.Report(snapshot); + + long after = 0; + while (true) + { + ct.ThrowIfCancellationRequested(); + var batch = await env.Storage.Imports.ListFilesAsync( + new ImportFileQuery { RunId = run.Id, State = ImportFileState.Pending, AfterId = after, Limit = BatchSize }, + ct).ConfigureAwait(false); + if (batch.Count == 0) + { + break; + } + + after = batch[^1].Id; + var facts = new ContentFacts[batch.Count]; + await Parallel.ForAsync( + 0, + batch.Count, + new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, env.Parallelism), CancellationToken = ct }, + async (i, token) => facts[i] = await ContentAnalysis.AnalyzeAsync(LibraryLayout.FullPath(layout.Root, batch[i].RelativePath), env, token).ConfigureAwait(false)) + .ConfigureAwait(false); + + var updates = new List(batch.Count); + for (var i = 0; i < batch.Count; i++) + { + var file = batch[i]; + var fact = facts[i]; + if (fact.Error is { } error) + { + updates.Add(file with { State = ImportFileState.Failed, LastError = error }); + continue; + } + + var hints = recognizers.Recognize(new ImportFileContext(layout, file.RelativePath)); + var (takenAt, source) = ResolveDate(hints, fact.MetadataDate, file.ModifiedAt); + var analysed = file with + { + Bytes = fact.Bytes, + MediaKind = fact.Type?.Kind, + ContentType = fact.Type?.ContentType, + Width = fact.Width, + Height = fact.Height, + Duration = fact.Duration, + Sha256 = fact.Sha256, + PerceptualHash = fact.PerceptualHash, + TakenAt = takenAt, + DateSource = source, + InstagramId = hints.InstagramId, + Code = hints.Code, + ProbableAccount = hints.AccountUsername, + ProbableKind = hints.Kind, + HighlightTitle = hints.HighlightTitle, + }; + + if (!targets.TryGetValue(file.Folder, out var target)) + { + target = file.TargetAccountId ?? await FindAccountAsync(hints, ct).ConfigureAwait(false); + targets[file.Folder] = target; + } + + var comparison = await comparer.CompareAsync(analysed, hints, target, ct).ConfigureAwait(false); + if (comparison.Pair is { } pair) + { + await env.Storage.Duplicates.AddAsync(pair, ct).ConfigureAwait(false); + } + + updates.Add(analysed with + { + Outcome = comparison.Outcome, + MatchedMediaId = comparison.MatchedMediaId, + State = ImportFileState.Analyzed, + LastError = comparison.Note, + }); + } + + await env.Storage.Imports.UpdateFilesAsync(updates, ct).ConfigureAwait(false); + foreach (var update in updates) + { + done++; + bytesDone += update.Bytes; + outcomes[update.Outcome] = outcomes.GetValueOrDefault(update.Outcome) + 1; + } + + progress?.Report(new ImportProgress(run.Id, ImportPhase.Analyzing, done, snapshot.FilesTotal, bytesDone, snapshot.BytesTotal, batch[^1].RelativePath, new Dictionary(outcomes), 0, env.Clock.Now)); + } + } + + /// + /// The date of a file, in the order of spec §9.2: name (or Febe's own journal), metadata, modification time. When + /// the name gives only the day, a metadata time on that same day is preferred. + /// + private (DateTimeOffset TakenAt, ImportDateSource Source) ResolveDate(FileHints hints, DateTimeOffset? metadata, DateTimeOffset? modified) + { + if (hints.Date is { } named && hints.DateSource is { } namedSource) + { + if (hints.DateIsDayOnly && metadata is { } exact + && LocalCalendar.Today(exact, env.Clock.LocalZone) == LocalCalendar.Today(named, env.Clock.LocalZone)) + { + return (exact, ImportDateSource.Metadata); + } + + return (named, namedSource); + } + + if (metadata is { } fromMetadata) + { + return (fromMetadata, ImportDateSource.Metadata); + } + + return (modified ?? env.Clock.Now, ImportDateSource.ModifiedTime); + } + + /// The account a folder probably goes to: by Instagram identifier, then by user name. + private async Task FindAccountAsync(FileHints hints, CancellationToken ct) + { + if (hints.AccountInstagramId is { } id && await env.Storage.Accounts.FindByInstagramIdAsync(id, ct).ConfigureAwait(false) is { } byId) + { + return byId.Id; + } + + return hints.AccountUsername is { } username && await env.Storage.Accounts.FindByUsernameAsync(username, ct).ConfigureAwait(false) is { } byName + ? byName.Id + : null; + } + + /// + /// The starting association of each folder (mockup 09): the existing account with that identifier or name, otherwise + /// a new «Solo archivio» account named after the folder when the name can be a user name, otherwise none («Scegli un + /// account…»). Folders Alberto has already associated are left alone. + /// + private async Task ApplyDefaultTargetsAsync(ImportRun run, SourceLayout layout, ImportRecognizers recognizers, CancellationToken ct) + { + var newAccounts = new Dictionary(await ImportRunSettings.GetNewAccountsAsync(env.Storage.Settings, run.Id, ct).ConfigureAwait(false), StringComparer.Ordinal); + var changed = false; + foreach (var folder in await env.Storage.Imports.ListFolderCountsAsync(run.Id, ct).ConfigureAwait(false)) + { + if (folder.TargetAccountId is not null || newAccounts.ContainsKey(folder.Folder)) + { + continue; + } + + var first = (await env.Storage.Imports.ListFilesAsync(new ImportFileQuery { RunId = run.Id, Folder = folder.Folder, Limit = 1 }, ct).ConfigureAwait(false)).FirstOrDefault(); + var hints = first is null ? new FileHints() : recognizers.Recognize(new ImportFileContext(layout, first.RelativePath)); + var username = hints.AccountUsername ?? folder.ProbableAccount; + if (await FindAccountAsync(hints with { AccountUsername = username }, ct).ConfigureAwait(false) is { } accountId) + { + await env.Storage.Imports.SetFolderTargetAsync(run.Id, folder.Folder, accountId, ct).ConfigureAwait(false); + } + else if (SourceLayout.UsernameFrom(username) is { } valid) + { + newAccounts[folder.Folder] = valid; + changed = true; + } + } + + if (changed) + { + await ImportRunSettings.SetNewAccountsAsync(env.Storage.Settings, run.Id, newAccounts, ct).ConfigureAwait(false); + } + } + + private Task WriteEventAsync(string code, string message, EventSeverity severity) => + env.Storage.Events.AppendAsync(new EventRecord { At = env.Clock.Now, Code = code, Message = message, Severity = severity }, CancellationToken.None); + + internal static string ErrorText(Exception ex) => ex switch + { + ImportSourceException source => source.Message, + IOException io => $"Errore di lettura o scrittura: {io.Message}", + UnauthorizedAccessException => "Febe non ha il permesso di leggere o scrivere un file: controlla i permessi della cartella.", + _ => $"Errore inatteso ({ex.GetType().Name}): riprova; se si ripete, segnalalo.", + }; +} diff --git a/src/Febe.Core/Import/ImportComparer.cs b/src/Febe.Core/Import/ImportComparer.cs new file mode 100644 index 0000000..03eff3b --- /dev/null +++ b/src/Febe.Core/Import/ImportComparer.cs @@ -0,0 +1,299 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Import; + +/// What the comparison decided for one file. +internal sealed record Comparison(ImportOutcome Outcome, long? MatchedMediaId, DuplicatePair? Pair, string? Note); + +/// +/// The comparison with the library (spec §9.3), for one analysis session. In this order: +/// +/// same SHA-256 as a library file present in any account → «Già in libreria» (the destination account first); +/// a file Alberto deleted «ricordando la scelta» counts too, so a deletion is not undone by an import; +/// same SHA-256 as an earlier file of the source → identical copy in the source; +/// same Instagram identifier or code with a different file → «Doppione probabile» (destination account first, then +/// the rest of the library); +/// perceptual hash within of a library photo → «Doppione +/// probabile» (destination account first); +/// the same two checks against earlier files of the source; +/// otherwise «Nuovo». +/// +/// Videos have no perceptual hash: for them only SHA-256 and identifiers count. One pair at most per file, with its +/// best match. Pairs inside the source always point to the first file of the group. +/// +internal sealed class ImportComparer +{ + private readonly IFebeStorage _storage; + private readonly PerceptualHashIndex _library; + private readonly Func _now; + private readonly Dictionary> _entriesById = new(StringComparer.Ordinal); + private readonly Dictionary> _entriesByCode = new(StringComparer.Ordinal); + private readonly Dictionary> _mediaById = new(StringComparer.Ordinal); + private readonly Dictionary> _mediaOfEntry = []; + private readonly Dictionary _entries = []; + + // The source: first file by SHA-256, by identity, and the perceptual hashes of the files that are «Nuovo». + private readonly Dictionary _sourceSha = new(StringComparer.Ordinal); + private readonly Dictionary _sourceIdentity = new(StringComparer.Ordinal); + private readonly PerceptualHashIndex _sourceHashes = new(); + + private ImportComparer(IFebeStorage storage, PerceptualHashIndex library, Func now) + { + _storage = storage; + _library = library; + _now = now; + } + + /// Loads the library identifiers and, when resuming, the files of the source already analysed. + /// The database. + /// The library's perceptual hashes (loaded from the database when null). + /// The import. + /// The recognizers' hints of a file already analysed (positions are not stored). + /// Current time. + /// Cancellation. + public static async Task CreateAsync( + IFebeStorage storage, + PerceptualHashIndex? sharedIndex, + long runId, + Func hintsOf, + Func now, + CancellationToken ct) + { + var library = sharedIndex; + if (library is null) + { + library = new PerceptualHashIndex(); + library.Load(await storage.Media.LoadPerceptualHashesAsync(ct).ConfigureAwait(false)); + } + + var comparer = new ImportComparer(storage, library, now); + var identifiers = await storage.Imports.LoadLibraryIdentifiersAsync(ct).ConfigureAwait(false); + foreach (var entry in identifiers.Entries) + { + comparer._entries[entry.EntryId] = entry; + if (entry.InstagramId is { } id) + { + Add(comparer._entriesById, id, entry); + } + + if (entry.Code is { } code) + { + Add(comparer._entriesByCode, code, entry); + } + } + + foreach (var media in identifiers.Media) + { + Add(comparer._mediaById, media.InstagramId, media); + } + + long after = 0; + while (true) + { + var page = await storage.Imports.ListFilesAsync(new ImportFileQuery { RunId = runId, AfterId = after, Limit = 5000 }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + foreach (var file in page.Where(f => f.Outcome != ImportOutcome.Pending)) + { + var hints = hintsOf(file); + comparer.Remember(file, file.Outcome, IdentityKeys(hints.InstagramId, hints.Code, hints.MediaInstagramId, hints.Position)); + } + + after = page[^1].Id; + } + + return comparer; + } + + /// + /// Compares a file (its must be set) with the library and with the earlier files of the + /// source, then remembers it for the files that follow. + /// + public async Task CompareAsync(ImportFile file, FileHints hints, long? targetAccountId, CancellationToken ct) + { + var comparison = await ClassifyAsync(file, hints, targetAccountId, ct).ConfigureAwait(false); + Remember(file, comparison.Outcome, IdentityKeys(hints.InstagramId, hints.Code, hints.MediaInstagramId, hints.Position)); + return comparison; + } + + private async Task ClassifyAsync(ImportFile file, FileHints hints, long? target, CancellationToken ct) + { + if (file.MediaKind is null || file.Sha256 is null) + { + return new Comparison(ImportOutcome.Unrecognized, null, null, ImportText.NoteNotRecognized); + } + + // 1. Same bytes anywhere in the library. + var same = await _storage.Media.FindBySha256Async(file.Sha256, ct).ConfigureAwait(false); + var present = same.Where(s => EntryStateRules.IsPresent(s.Media.State)).OrderBy(s => s.Entry.AccountId == target ? 0 : 1).ThenBy(s => s.Media.Id).FirstOrDefault(); + if (present is not null) + { + return new Comparison(ImportOutcome.AlreadyInLibrary, present.Media.Id, null, null); + } + + if (same.FirstOrDefault(s => s.Media.State == MediaState.Deleted || s.Entry.State == EntryState.Deleted) is { } deleted) + { + return new Comparison(ImportOutcome.AlreadyInLibrary, deleted.Media.Id, null, ImportText.NoteDeletedByAlberto); + } + + // 2. Same bytes earlier in the source. + if (_sourceSha.TryGetValue(file.Sha256, out var twin) && twin.Id != file.Id) + { + return new Comparison(ImportOutcome.IdenticalInSource, null, null, $"Uguale a «{twin.Path}» della stessa sorgente."); + } + + // 3. Same identifier, different file, in the library. + if (await MatchIdentityAsync(file, hints, target, ct).ConfigureAwait(false) is { } byIdentity) + { + return byIdentity; + } + + // 4. Visually similar to a library photo. + if (file.PerceptualHash is { } hash + && _library.FindSimilar(hash, PerceptualHash.DuplicateThreshold, target, limit: 1) is [var similar, ..]) + { + return Pair(file, DuplicateReason.VisuallySimilar, similar.MediaId, null, similar.Distance); + } + + // 5. Same identity or similar image earlier in the source. + foreach (var key in IdentityKeys(hints.InstagramId, hints.Code, hints.MediaInstagramId, hints.Position)) + { + if (_sourceIdentity.TryGetValue(key, out var first) && first != file.Id) + { + return Pair(file, DuplicateReason.SameInstagramId, null, first, null); + } + } + + if (file.PerceptualHash is { } h && _sourceHashes.FindSimilar(h, PerceptualHash.DuplicateThreshold, excludeMediaId: file.Id, limit: 1) is [var near, ..]) + { + return Pair(file, DuplicateReason.VisuallySimilar, null, near.MediaId, near.Distance); + } + + return new Comparison(ImportOutcome.New, null, null, null); + } + + private async Task MatchIdentityAsync(ImportFile file, FileHints hints, long? target, CancellationToken ct) + { + var candidates = new List<(EntryIdentity Entry, long? MediaId)>(); + foreach (var id in new[] { hints.MediaInstagramId, hints.InstagramId }.OfType().Distinct(StringComparer.Ordinal)) + { + foreach (var media in _mediaById.GetValueOrDefault(id) ?? []) + { + if (EntryOf(media.EntryId) is { } owner) + { + candidates.Add((owner, media.MediaId)); + } + } + } + + if (hints.InstagramId is { } entryId) + { + candidates.AddRange((_entriesById.GetValueOrDefault(entryId) ?? []).Select(e => (e, (long?)null))); + } + + if (hints.Code is { } code) + { + candidates.AddRange((_entriesByCode.GetValueOrDefault(code) ?? []).Select(e => (e, (long?)null))); + } + + foreach (var (entry, mediaId) in candidates.OrderBy(c => c.Entry.AccountId == target ? 0 : 1).ThenBy(c => c.MediaId is null ? 1 : 0)) + { + if (entry.State == EntryState.Deleted) + { + return new Comparison(ImportOutcome.AlreadyInLibrary, null, null, ImportText.NoteDeletedByAlberto); + } + + if (!_mediaOfEntry.TryGetValue(entry.EntryId, out var files)) + { + files = await _storage.Media.ListByEntryAsync(entry.EntryId, ct).ConfigureAwait(false); + _mediaOfEntry[entry.EntryId] = files; + } + + var chosen = mediaId is { } m ? files.FirstOrDefault(f => f.Id == m) + : hints.Position is { } p ? files.FirstOrDefault(f => f.Position == p) + : files.Count == 1 ? files[0] : null; + if (chosen is not null && EntryStateRules.IsPresent(chosen.State) && !string.Equals(chosen.Sha256, file.Sha256, StringComparison.Ordinal)) + { + return Pair(file, DuplicateReason.SameInstagramId, chosen.Id, null, null); + } + } + + return null; + } + + private EntryIdentity? EntryOf(long entryId) => _entries.GetValueOrDefault(entryId); + + private Comparison Pair(ImportFile file, DuplicateReason reason, long? existingMediaId, long? existingFileId, int? distance) => new( + ImportOutcome.ProbableDuplicate, + existingMediaId, + new DuplicatePair + { + Origin = DuplicateOrigin.Import, + Reason = reason, + ExistingMediaId = existingMediaId, + ExistingImportFileId = existingFileId, + CandidateImportFileId = file.Id, + Distance = distance, + CreatedAt = _now(), + }, + null); + + private void Remember(ImportFile file, ImportOutcome outcome, IEnumerable identityKeys) + { + if (file.Sha256 is { } sha && outcome != ImportOutcome.Unrecognized) + { + _sourceSha.TryAdd(sha, (file.Id, file.RelativePath)); + } + + if (outcome != ImportOutcome.New) + { + return; // pairs inside the source point to the first file of a group + } + + foreach (var key in identityKeys) + { + _sourceIdentity.TryAdd(key, file.Id); + } + + if (file.PerceptualHash is { } hash) + { + _sourceHashes.Add(file.Id, 0, hash); + } + } + + /// Keys that identify the same Instagram file: the item's own id, or the entry id/code with the position. + private static IEnumerable IdentityKeys(string? instagramId, string? code, string? mediaInstagramId, int? position) + { + if (mediaInstagramId is not null) + { + yield return "m:" + mediaInstagramId; + } + + var n = (position ?? 1).ToString(System.Globalization.CultureInfo.InvariantCulture); + if (instagramId is not null) + { + yield return "i:" + instagramId + "#" + n; + } + + if (code is not null) + { + yield return "c:" + code + "#" + n; + } + } + + private static void Add(Dictionary> map, string key, T value) + { + if (!map.TryGetValue(key, out var list)) + { + list = []; + map[key] = list; + } + + list.Add(value); + } +} diff --git a/src/Febe.Core/Import/ImportCopier.cs b/src/Febe.Core/Import/ImportCopier.cs new file mode 100644 index 0000000..f039f06 --- /dev/null +++ b/src/Febe.Core/Import/ImportCopier.cs @@ -0,0 +1,759 @@ +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Import; + +/// +/// Step 4 of the import (spec §9.4): copy or move with verification, then the report. +/// +/// Files enter the library through , like downloads: safe write with SHA-256, thumbnails, +/// perceptual hashes, _febe.jsonl line, provenance «importato». Nothing is ever overwritten. +/// Files with a known date and code take the name of the library scheme; the others go to +/// importati/ with their original name. +/// «Sposta» deletes an original only after the copy on disk has been hashed again and matches; never when the +/// source is read-only. If the copy does not match, the original stays. +/// «Tieni il più grande», when the source file is larger, replaces the library file: only on Alberto's explicit +/// choice (rule 12). The new file is written and verified first, then the record and the journal are updated, and only +/// then is the old file removed. +/// Resumable: every file has its state; an interrupted copy continues where it stopped (an entry created just before +/// an interruption is reused, not duplicated). +/// +/// +public sealed class ImportCopier(ImportEnvironment env) +{ + private const string ImportedFolder = "importati"; + + /// + /// Runs (or resumes) the copy of an import. Files that stay out (folder without account, undecided duplicates) keep + /// their state: after a change in the review the copy can run again on the same import and takes them. + /// On cancellation the import becomes «copia interrotta» and is thrown. + /// + public async Task CopyAsync(long runId, IProgress? progress = null, CancellationToken ct = default) + { + var run = await env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Importazione {runId} non trovata."); + if (run.State is not (ImportRunState.Reviewing or ImportRunState.Copying or ImportRunState.CopyInterrupted or ImportRunState.Completed)) + { + throw new InvalidOperationException(run.State is ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted + ? "L'analisi non è finita: riprendila prima di importare." + : "Questa importazione è stata annullata."); + } + + if (run.Mode == ImportMode.Move && run.SourceReadOnly) + { + throw new InvalidOperationException("La sorgente è in sola lettura: si può solo copiare."); + } + + run = run with { State = ImportRunState.Copying, LastError = null }; + await env.Storage.Imports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false); + var tally = new Tally(); + try + { + if (!Directory.Exists(run.SourcePath)) + { + throw new ImportSourceException($"La cartella {run.SourcePath} non si trova più: ricollega il disco e riprendi l'importazione."); + } + + await CreateNewAccountsAsync(run, ct).ConfigureAwait(false); + var layout = SourceLayout.Inspect(run.SourcePath); + var recognizers = ImportRecognizers.Create( + env.Clock.LocalZone, + () => env.Clock.Now, + await ImportRunSettings.GetStogramAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false)); + await recognizers.PrepareAsync(layout, ct).ConfigureAwait(false); + + var files = await LoadFilesAsync(runId, ct).ConfigureAwait(false); + var planner = await ImportPlanner.LoadAsync(env.Storage, runId, files, ct).ConfigureAwait(false); + var ingest = new LibraryIngest(env.Storage, env.Layout, env.Naming, env.Journal, env.Clock, env.Thumbnails, hashIndex: null, env.SetFileTimeToPublication); + var context = new CopyContext(run, layout, recognizers, ingest); + var total = files.Count; + var bytesTotal = files.Values.Sum(f => f.Bytes); + var done = 0; + long bytesDone = 0; + var copied = files.Values.Count(f => f.State is ImportFileState.Copied or ImportFileState.Moved); + foreach (var file in files.Values.OrderBy(f => f.Id)) + { + ct.ThrowIfCancellationRequested(); + var current = file; + if (run.Mode == ImportMode.Move && file.State == ImportFileState.Copied && file.EntryId is not null + && file.LastError is { } pending && (pending.EndsWith(ImportText.NoteMovePending, StringComparison.Ordinal) || pending.EndsWith(ImportText.NoteOriginalKept, StringComparison.Ordinal))) + { + // A move interrupted between the copy and the deletion of the original (or a deletion that failed). + // Files copied earlier under «Copia» carry no such note: their originals are never deleted. + current = await FinishMoveAsync(context, file, tally).ConfigureAwait(false); + } + else + { + var planned = planner.Classify(file); + current = await ApplyAsync(context, planned, tally, ct).ConfigureAwait(false); + if (current.State is ImportFileState.Copied or ImportFileState.Moved && file.State is not (ImportFileState.Copied or ImportFileState.Moved)) + { + copied++; + } + } + + done++; + bytesDone += file.Bytes; + progress?.Report(new ImportProgress(runId, ImportPhase.Copying, done, total, bytesDone, bytesTotal, file.RelativePath, new Dictionary(), copied, env.Clock.Now)); + } + + run = run with { State = ImportRunState.Completed, CompletedAt = env.Clock.Now, LastError = null }; + await env.Storage.Imports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false); + await env.Storage.Events.AppendAsync( + new EventRecord + { + At = env.Clock.Now, + Code = "importazione-completata", + Message = CompletionMessage(layout.RootName, tally), + Severity = tally.Failed > 0 ? EventSeverity.Warning : EventSeverity.Success, + }, + CancellationToken.None).ConfigureAwait(false); + progress?.Report(new ImportProgress(runId, ImportPhase.Finished, done, total, bytesDone, bytesDone, null, new Dictionary(), copied, env.Clock.Now)); + return run; + } + catch (Exception ex) + { + var cancelled = ex is OperationCanceledException && ct.IsCancellationRequested; + run = run with { State = ImportRunState.CopyInterrupted, LastError = cancelled ? null : ImportAnalyzer.ErrorText(ex) }; + await env.Storage.Imports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false); + throw; + } + } + + private static string CompletionMessage(string source, Tally tally) + { + var text = $"Importazione dalla cartella «{source}» finita: {ImportText.Count(tally.Copied, "file importato", "file importati")}"; + if (tally.Replaced > 0) + { + text += $" ({ImportText.Count(tally.Replaced, "al posto di un file più piccolo", "al posto di file più piccoli")})"; + } + + if (tally.LeftOut > 0) + { + text += ", " + ImportText.Count(tally.LeftOut, "file resta fuori", "file restano fuori"); + } + + if (tally.Failed > 0) + { + text += ", " + ImportText.Count(tally.Failed, "file non riuscito", "file non riusciti"); + } + + return text + "."; + } + + private async Task> LoadFilesAsync(long runId, CancellationToken ct) + { + var files = new Dictionary(); + long after = 0; + while (true) + { + var page = await env.Storage.Imports.ListFilesAsync(new ImportFileQuery { RunId = runId, AfterId = after, Limit = 10_000 }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + foreach (var file in page) + { + files[file.Id] = file; + } + + after = page[^1].Id; + } + + return files; + } + + /// Creates the «Solo archivio» accounts chosen in the review and associates their folders. + private async Task CreateNewAccountsAsync(ImportRun run, CancellationToken ct) + { + var intents = await ImportRunSettings.GetNewAccountsAsync(env.Storage.Settings, run.Id, ct).ConfigureAwait(false); + if (intents.Count == 0) + { + return; + } + + foreach (var (folder, username) in intents) + { + var account = await env.Storage.Accounts.FindByUsernameAsync(username, ct).ConfigureAwait(false); + if (account is null) + { + var now = env.Clock.Now; + account = await env.Storage.Accounts.AddAsync( + Account.Create(username, StartingPoint.EverythingAndKeepUpdated, now, env.Clock.LocalZone) with + { + State = AccountState.ArchiveOnly, + KeepUpdated = false, + StateChangedAt = now, + }, + CancellationToken.None).ConfigureAwait(false); + await env.Storage.Events.AppendAsync( + new EventRecord { At = now, Code = "account-solo-archivio", Message = $"Account {account.Username} creato dall'importazione, «Solo archivio».", AccountId = account.Id }, + CancellationToken.None).ConfigureAwait(false); + } + + await env.Storage.Imports.SetFolderTargetAsync(run.Id, folder, account.Id, CancellationToken.None).ConfigureAwait(false); + } + + await ImportRunSettings.SetNewAccountsAsync(env.Storage.Settings, run.Id, new Dictionary(), CancellationToken.None).ConfigureAwait(false); + } + + private async Task ApplyAsync(CopyContext context, PlannedFile planned, Tally tally, CancellationToken ct) + { + var file = planned.File; + switch (planned.Action) + { + case PlannedAction.Done or PlannedAction.NotAnalyzed: + return file; + case PlannedAction.Skip: + tally.Skipped++; + return await SaveAsync(file with { State = ImportFileState.Skipped, LastError = planned.Note }).ConfigureAwait(false); + case PlannedAction.WaitNoAccount or PlannedAction.WaitDecision: + tally.LeftOut++; + return file.LastError == planned.Note ? file : await SaveAsync(file with { LastError = planned.Note }).ConfigureAwait(false); + default: + break; + } + + try + { + return planned.Action == PlannedAction.Replace + ? await ReplaceAsync(context, file, planned.ReplaceMediaId!.Value, tally, ct).ConfigureAwait(false) + : await ImportAsync(context, file, tally, ct).ConfigureAwait(false); + } + catch (ContentChangedException) + { + tally.Failed++; + return await SaveAsync(file with { State = ImportFileState.Failed, LastError = ImportText.NoteChanged }).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + tally.Failed++; + return await SaveAsync(file with { State = ImportFileState.Failed, LastError = ImportAnalyzer.ErrorText(ex) }).ConfigureAwait(false); + } + } + + /// Copies one file into its destination account as an imported entry (or into an entry it completes). + private async Task ImportAsync(CopyContext context, ImportFile file, Tally tally, CancellationToken ct) + { + var source = LibraryLayout.FullPath(context.Layout.Root, file.RelativePath); + + // The library may have received the same bytes since the analysis (an identical copy met earlier in the source). + var same = await env.Storage.Media.FindBySha256Async(file.Sha256!, ct).ConfigureAwait(false); + if (same.FirstOrDefault(s => EntryStateRules.IsPresent(s.Media.State)) is { } twin && file.EntryId is null) + { + tally.Skipped++; + return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = twin.Media.Id, LastError = ImportText.NoteAlreadyInLibrary }).ConfigureAwait(false); + } + + var account = await env.Storage.Accounts.GetAsync(file.TargetAccountId!.Value, ct).ConfigureAwait(false) + ?? throw new InvalidOperationException("L'account di destinazione non esiste più: associa di nuovo la cartella."); + var hints = context.Recognizers.Recognize(new ImportFileContext(context.Layout, file.RelativePath)); + var target = await ResolveTargetAsync(account, file, hints, ct).ConfigureAwait(false); + if (target.Deleted) + { + tally.Skipped++; + return await SaveAsync(file with { State = ImportFileState.Skipped, LastError = ImportText.NoteDeletedByAlberto }).ConfigureAwait(false); + } + + var (entry, media) = (target.Entry!, target.Media!); + if (file.EntryId != entry.Id) + { + file = await SaveAsync(file with { EntryId = entry.Id }).ConfigureAwait(false); // a resumed copy reuses this entry + } + + if (EntryStateRules.IsPresent(media.State) && string.Equals(media.Sha256, file.Sha256, StringComparison.Ordinal) && media.RelativePath is { } already) + { + // Stored before an interruption: only the journal line and the state are missing. + await context.Ingest.AppendJournalAsync(entry.Id, CancellationToken.None).ConfigureAwait(false); + return await FinishAsync(context, file, account, entry.Id, already, null, tally).ConfigureAwait(false); + } + + var byScheme = target.ByScheme && file.DateSource is ImportDateSource.FileName or ImportDateSource.Journal or ImportDateSource.Metadata; + MediaSaveResult result; + try + { + await using var content = env.FileSystem.OpenRead(source); + using var cover = file.MediaKind == MediaKind.Video ? await FrameAsync(source, ct).ConfigureAwait(false) : null; + result = await context.Ingest.SaveMediaAsync( + account, + entry, + media, + new MediaContent + { + Content = content, + Extension = Extension(file, source), + Cover = cover, + FixedRelativePath = byScheme ? null : ImportedFolder + "/" + Path.GetFileName(source), + ExpectedSha256 = file.Sha256, + }, + file.HighlightTitle, + ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or OperationCanceledException) + { + // Nothing was written under a final name. A record made for this file alone goes too, so that the library + // does not show an empty entry; a resumed copy would make it again. + if (target.OwnedByThisFile) + { + await RemoveIfEmptyAsync(entry.Id).ConfigureAwait(false); + await SaveAsync(file with { EntryId = null }).ConfigureAwait(false); + } + + throw; + } + + if (result.Outcome == MediaSaveOutcome.IdenticalInAccount) + { + if (target.OwnedByThisFile) + { + await RemoveIfEmptyAsync(entry.Id).ConfigureAwait(false); + } + + tally.Skipped++; + return await SaveAsync(file with { State = ImportFileState.Skipped, EntryId = null, MatchedMediaId = result.Identical?.Media.Id, LastError = ImportText.NoteAlreadyInLibrary }).ConfigureAwait(false); + } + + if (result.File!.PerceptualHash is { } hash) + { + env.HashIndex?.Add(media.Id, account.Id, hash); + } + + if (entry.Kind == EntryKind.Highlight && file.HighlightTitle is { } title) + { + var none = CancellationToken.None; + var collection = await env.Storage.Highlights.FindByTitleAsync(account.Id, title, none).ConfigureAwait(false) + ?? await env.Storage.Highlights.UpsertAsync(new Highlight { AccountId = account.Id, Title = title, DiscoveredAt = env.Clock.Now }, none).ConfigureAwait(false); + await env.Storage.Highlights.AddItemAsync(collection.Id, entry.Id, none).ConfigureAwait(false); + } + + await context.Ingest.AppendJournalAsync(entry.Id, CancellationToken.None).ConfigureAwait(false); + return await FinishAsync(context, file, account, entry.Id, result.File.RelativePath, null, tally).ConfigureAwait(false); + } + + /// The entry that receives the file. + /// The file record to fill. + /// The entry has an identity: the file may take the scheme name. + /// The entry was deleted by Alberto «ricordando la scelta»: the file is not imported. + /// The entry exists only for this file (created by this import for it). + private sealed record Target(Entry? Entry, Media? Media, bool ByScheme, bool Deleted, bool OwnedByThisFile = false); + + /// + /// The entry and file record that receive a source file: the one created by an interrupted attempt; an entry of the + /// destination account with the same identifier or code (a file it lacks is added or filled, as when an import + /// completes a series); or a new imported entry. When the position is already taken by another file (Alberto chose + /// «Tienili entrambi»), the file gets an entry of its own without identifier, in importati/. + /// + private async Task ResolveTargetAsync(Account account, ImportFile file, FileHints hints, CancellationToken ct) + { + var kind = file.ProbableKind ?? EntryKind.Post; + var position = hints.Position is >= 1 ? hints.Position.Value : 1; + if (file.EntryId is { } previous && await env.Storage.Entries.GetWithMediaAsync(previous, ct).ConfigureAwait(false) is { } resumed) + { + var known = resumed.Entry.InstagramId is not null || resumed.Entry.Code is not null; + var existing = resumed.Media.FirstOrDefault(m => m.Position == (known ? position : 1)); + var usable = existing is not null && (!EntryStateRules.IsPresent(existing.State) || string.Equals(existing.Sha256, file.Sha256, StringComparison.Ordinal)); + if (usable) + { + var owned = resumed.Entry.Provenance == Provenance.Imported && resumed.Media.Count == 1; + return new Target(resumed.Entry, existing, known, false, owned); + } + } + + if (file.InstagramId is not null || file.Code is not null) + { + var same = file.InstagramId is { } id + ? await env.Storage.Entries.FindAsync(account.Id, kind, id, ct).ConfigureAwait(false) + : await env.Storage.Imports.FindEntryByCodeAsync(account.Id, kind, file.Code!, ct).ConfigureAwait(false); + if (same is not null) + { + if (same.State == EntryState.Deleted) + { + return new Target(null, null, false, true); + } + + var files = await env.Storage.Media.ListByEntryAsync(same.Id, ct).ConfigureAwait(false); + var slot = files.FirstOrDefault(m => m.Position == position); + if (slot is null) + { + var added = await env.Storage.Media.AddToEntryAsync(same.Id, [NewMedia(file, hints, position)], ct).ConfigureAwait(false); + return new Target(same, added.First(m => m.Position == position), true, false); + } + + if (!EntryStateRules.IsPresent(slot.State) && slot.State != MediaState.Deleted) + { + return new Target(same, slot, true, false); // a file still to download: the import fills it + } + } + else + { + var created = await env.Storage.Entries.AddAsync(NewEntry(account, file, hints, kind, withIdentity: true), [NewMedia(file, hints, position)], ct).ConfigureAwait(false); + if (created.Created) + { + return new Target(created.Stored.Entry, created.Stored.Media[0], true, false, true); + } + } + } + + var plain = await env.Storage.Entries.AddAsync(NewEntry(account, file, hints, kind, withIdentity: false), [NewMedia(file, hints, 1) with { InstagramId = null }], ct).ConfigureAwait(false); + return new Target(plain.Stored.Entry, plain.Stored.Media[0], false, false, true); + } + + private Entry NewEntry(Account account, ImportFile file, FileHints hints, EntryKind kind, bool withIdentity) => new() + { + AccountId = account.Id, + Kind = kind, + InstagramId = withIdentity ? file.InstagramId : null, + Code = withIdentity ? file.Code : null, + PublishedAt = file.TakenAt ?? file.ModifiedAt ?? env.Clock.Now, + Caption = withIdentity ? hints.Caption : null, + AuthorUsername = withIdentity ? hints.AuthorUsername : null, + AuthorInstagramId = withIdentity ? hints.AuthorInstagramId : null, + Provenance = Provenance.Imported, + State = EntryState.ToDownload, + DiscoveredAt = env.Clock.Now, + }; + + private static Media NewMedia(ImportFile file, FileHints hints, int position) => new() + { + Position = position, + Kind = file.MediaKind ?? MediaKind.Photo, + InstagramId = hints.MediaInstagramId, + Width = file.Width, + Height = file.Height, + Duration = file.Duration, + State = MediaState.ToDownload, + }; + + /// + /// «Tieni il più grande» with the source file larger: writes the new file next to the old one, verifies it, points + /// the library record and the journal at it, then removes the old file (rule 12: only on Alberto's choice). + /// + private async Task ReplaceAsync(CopyContext context, ImportFile file, long mediaId, Tally tally, CancellationToken ct) + { + var media = await env.Storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false); + if (media is null || !EntryStateRules.IsPresent(media.State) || media.RelativePath is null) + { + return await ImportAsync(context, file, tally, ct).ConfigureAwait(false); // the library file is gone meanwhile + } + + if (string.Equals(media.Sha256, file.Sha256, StringComparison.Ordinal)) + { + return await FinishAsync(context, file, (await AccountOfEntryAsync(media.EntryId, ct).ConfigureAwait(false)).Account, media.EntryId, media.RelativePath, ImportText.NoteReplaced, tally).ConfigureAwait(false); + } + + var (account, entry) = await AccountOfEntryAsync(media.EntryId, ct).ConfigureAwait(false); + var folder = env.Layout.AccountFolder(account); + var source = LibraryLayout.FullPath(context.Layout.Root, file.RelativePath); + var oldRelative = media.RelativePath; + var oldFull = LibraryLayout.FullPath(folder, oldRelative); + var highlights = await env.Storage.Highlights.ListForEntryAsync(entry.Id, ct).ConfigureAwait(false); + var newRelative = oldRelative.StartsWith(ImportedFolder + "/", StringComparison.Ordinal) + ? ImportedFolder + "/" + Path.GetFileName(source) + : env.Layout.RelativePathFor( + folder, + env.Naming.For(entry.Kind), + NamingValues.For(account.Username, entry, media.Position, Extension(file, source), highlights.FirstOrDefault()?.Title, file.Sha256), + env.Clock.LocalZone); + var directory = newRelative.Contains('/', StringComparison.Ordinal) ? newRelative[..newRelative.LastIndexOf('/')] : string.Empty; + + SavedFile saved; + await using (var content = env.FileSystem.OpenRead(source)) + { + saved = (await new SafeFileWriter(env.Layout.MaxPathLength).SaveAsync( + content, + folder, + directory, + (digest, _) => string.Equals(digest.Sha256, file.Sha256, StringComparison.Ordinal) + ? ValueTask.FromResult(newRelative) + : throw new ContentChangedException("Il file è cambiato dopo l'analisi."), + new SafeWriteOptions { LastWriteTime = env.SetFileTimeToPublication ? entry.PublishedAt : null }, + ct).ConfigureAwait(false))!; + } + + // From here the replacement goes to the end: a half-done replacement is worse than a late one. + var none = CancellationToken.None; + var onDisk = await env.FileSystem.ComputeSha256Async(saved.FullPath, none).ConfigureAwait(false); + if (!string.Equals(onDisk, file.Sha256, StringComparison.Ordinal)) + { + TryDelete(saved.FullPath); // the new file was never registered: nothing in the library points to it + tally.Failed++; + return await SaveAsync(file with { State = ImportFileState.Failed, LastError = ImportText.NoteNotVerified }).ConfigureAwait(false); + } + + ulong? hash = null; + int? width = file.Width, height = file.Height; + var thumbnail = false; + if (file.MediaKind == MediaKind.Photo) + { + hash = PerceptualHash.ComputeFromFile(saved.FullPath); + await using (var stream = File.OpenRead(saved.FullPath)) + { + if (ImageDecoding.ReadSize(stream) is { } size) + { + (width, height) = size; + } + } + + thumbnail = TryThumbnail(saved.Sha256, () => File.OpenRead(saved.FullPath)); + } + else if (await FrameAsync(source, none).ConfigureAwait(false) is { } frame) + { + using (frame) + { + thumbnail = TryThumbnail(saved.Sha256, () => frame); + } + } + + await env.Storage.Media.MarkStoredAsync( + media.Id, + new StoredFile(saved.RelativePath, saved.Bytes, saved.Sha256, hash, width, height, file.Duration ?? media.Duration, thumbnail), + media.State, + env.Clock.Now, + none).ConfigureAwait(false); + await context.Ingest.AppendJournalAsync(entry.Id, none).ConfigureAwait(false); + if (hash is { } h) + { + env.HashIndex?.Add(media.Id, account.Id, h); + } + else + { + env.HashIndex?.Remove(media.Id); + } + + var note = ImportText.NoteReplaced; + if (!TryDelete(oldFull)) + { + note += " " + ImportText.NoteOldNotDeleted; + } + + if (media.Sha256 is { } oldSha && env.Thumbnails is { } thumbnails) + { + var users = await env.Storage.Media.FindBySha256Async(oldSha, none).ConfigureAwait(false); + if (!users.Any(u => EntryStateRules.IsPresent(u.Media.State))) + { + try + { + thumbnails.Delete(oldSha); + } + catch (IOException) + { + // A thumbnail left behind costs a few kilobytes. + } + } + } + + tally.Replaced++; + return await FinishAsync(context, file with { MatchedMediaId = media.Id }, account, entry.Id, saved.RelativePath, note, tally).ConfigureAwait(false); + } + + /// Records a stored file; with «Sposta» verifies the copy on disk and only then deletes the original. + private async Task FinishAsync(CopyContext context, ImportFile file, Account account, long entryId, string relativePath, string? note, Tally tally) + { + tally.Copied++; + var copied = file with + { + State = ImportFileState.Copied, + EntryId = entryId, + DestinationPath = relativePath, + TargetAccountId = file.TargetAccountId ?? account.Id, + LastError = note, + }; + if (context.Run.Mode != ImportMode.Move || context.Run.SourceReadOnly) + { + return await SaveAsync(copied).ConfigureAwait(false); + } + + // Recorded first, so that a move interrupted here is finished (verification included) by the next run. + copied = await SaveAsync(copied with { LastError = Join(note, ImportText.NoteMovePending) }).ConfigureAwait(false); + return await MoveOriginalAsync(context, copied, LibraryLayout.FullPath(env.Layout.AccountFolder(account), relativePath), tally).ConfigureAwait(false); + } + + private async Task FinishMoveAsync(CopyContext context, ImportFile file, Tally tally) + { + var stored = await env.Storage.Entries.GetWithMediaAsync(file.EntryId!.Value, CancellationToken.None).ConfigureAwait(false); + var account = stored is null ? null : await env.Storage.Accounts.GetAsync(stored.Entry.AccountId, CancellationToken.None).ConfigureAwait(false); + if (account is null || file.DestinationPath is null) + { + return file; + } + + return await MoveOriginalAsync(context, file, LibraryLayout.FullPath(env.Layout.AccountFolder(account), file.DestinationPath), tally).ConfigureAwait(false); + } + + /// The safety rule of «Sposta»: hash the copy as it is on disk now; delete the original only on a match. + private async Task MoveOriginalAsync(CopyContext context, ImportFile file, string copyPath, Tally tally) + { + if (context.Run.SourceReadOnly) + { + return file; + } + + var original = LibraryLayout.FullPath(context.Layout.Root, file.RelativePath); + string? onDisk = null; + try + { + onDisk = await env.FileSystem.ComputeSha256Async(copyPath, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Unreadable copy: not verified. + } + + if (!string.Equals(onDisk, file.Sha256, StringComparison.Ordinal)) + { + tally.Copied--; + tally.Failed++; + return await SaveAsync(file with { State = ImportFileState.Failed, LastError = ImportText.NoteNotVerified }).ConfigureAwait(false); + } + + var note = WithoutMoveNotes(file.LastError); + try + { + if (File.Exists(original)) + { + env.FileSystem.DeleteOriginal(original); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return await SaveAsync(file with { LastError = Join(note, ImportText.NoteOriginalKept) }).ConfigureAwait(false); + } + + tally.Moved++; + return await SaveAsync(file with { State = ImportFileState.Moved, LastError = note }).ConfigureAwait(false); + } + + private async Task<(Account Account, Entry Entry)> AccountOfEntryAsync(long entryId, CancellationToken ct) + { + var entry = await env.Storage.Entries.GetAsync(entryId, ct).ConfigureAwait(false) + ?? throw new InvalidOperationException("L'elemento della libreria non esiste più."); + var account = await env.Storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) + ?? throw new InvalidOperationException("L'account dell'elemento non esiste più."); + return (account, entry); + } + + private async Task FrameAsync(string videoPath, CancellationToken ct) + { + if (env.Frames is null || env.Thumbnails is null) + { + return null; + } + + var frame = await env.Frames.ExtractJpegAsync(videoPath, ct).ConfigureAwait(false); + return frame is null ? null : new MemoryStream(frame, writable: false); + } + + private bool TryThumbnail(string key, Func open) + { + if (env.Thumbnails is null) + { + return false; + } + + try + { + using var stream = open(); + return env.Thumbnails.Create(key, stream); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException) + { + return false; + } + } + + /// Removes an entry this import created when it ended up without any file (identical content found). + private async Task RemoveIfEmptyAsync(long entryId) + { + var stored = await env.Storage.Entries.GetWithMediaAsync(entryId, CancellationToken.None).ConfigureAwait(false); + if (stored is { Entry.Provenance: Provenance.Imported } && stored.Media.All(m => !EntryStateRules.IsPresent(m.State))) + { + await env.Storage.Entries.RemoveAsync(entryId, CancellationToken.None).ConfigureAwait(false); + } + } + + /// The library extension: the detected format's (".jpeg" becomes ".jpg"), or the file's own for unknown ones. + private static string Extension(ImportFile file, string source) + { + var detected = file.ContentType is { } type ? MediaSnifferExtension(type) : null; + return detected ?? Path.GetExtension(source); + } + + private static string? MediaSnifferExtension(string contentType) => contentType switch + { + "image/jpeg" => ".jpg", + "image/png" => ".png", + "image/gif" => ".gif", + "image/webp" => ".webp", + "image/heic" => ".heic", + "image/heif" => ".heif", + "image/avif" => ".avif", + "image/bmp" => ".bmp", + "video/mp4" => ".mp4", + "video/quicktime" => ".mov", + "video/webm" => ".webm", + "video/x-matroska" => ".mkv", + "video/3gpp" => ".3gp", + "video/x-msvideo" => ".avi", + _ => null, // TIFF family and rarer formats keep their own extension + }; + + private Task SaveAsync(ImportFile file) => SaveCoreAsync(file); + + private async Task SaveCoreAsync(ImportFile file) + { + await env.Storage.Imports.UpdateFileAsync(file, CancellationToken.None).ConfigureAwait(false); + return file; + } + + private static string Join(string? first, string second) => string.IsNullOrEmpty(first) ? second : first + " " + second; + + private static string? WithoutMoveNotes(string? note) + { + if (note is null) + { + return null; + } + + var cleaned = note.Replace(ImportText.NoteMovePending, string.Empty, StringComparison.Ordinal) + .Replace(ImportText.NoteOriginalKept, string.Empty, StringComparison.Ordinal) + .Trim(); + return cleaned.Length == 0 ? null : cleaned; + } + + private static bool TryDelete(string path) + { + try + { + if (File.Exists(path)) + { + File.Delete(path); + } + + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + } + + private sealed record CopyContext(ImportRun Run, SourceLayout Layout, ImportRecognizers Recognizers, LibraryIngest Ingest); + + private sealed class Tally + { + public int Copied { get; set; } + + public int Moved { get; set; } + + public int Replaced { get; set; } + + public int Skipped { get; set; } + + public int LeftOut { get; set; } + + public int Failed { get; set; } + } +} diff --git a/src/Febe.Core/Import/ImportEnvironment.cs b/src/Febe.Core/Import/ImportEnvironment.cs new file mode 100644 index 0000000..e1d4cc1 --- /dev/null +++ b/src/Febe.Core/Import/ImportEnvironment.cs @@ -0,0 +1,169 @@ +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); +} diff --git a/src/Febe.Core/Import/ImportModels.cs b/src/Febe.Core/Import/ImportModels.cs new file mode 100644 index 0000000..3010b95 --- /dev/null +++ b/src/Febe.Core/Import/ImportModels.cs @@ -0,0 +1,224 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Import; + +/// Choices made when an import starts (step 1). +public sealed record ImportAnalysisOptions +{ + /// + /// Turns on the 4K Stogram recognizer, which is an unverified hypothesis (spec §9.6): off by default. The + /// interface may offer it when is true, saying that names are read + /// by a guess still to be checked on Alberto's real files. + /// + public bool StogramHypothesis { get; init; } +} + +/// The phase of an import job. +public enum ImportPhase +{ + /// «Elenco dei file»: the source is listed (read-only). + Listing, + + /// «Analisi»: type, hashes, dates and comparison with the library. + Analyzing, + + /// «Copia»: copy or move with verification. + Copying, + + /// The job ended (finished, interrupted or failed: see the run state). + Finished, +} + +/// Progress of an import job, for the bar of steps 2 and 4. +/// The import. +/// What is running. +/// Files analysed (or handled by the copy) so far, earlier sessions included. +/// Files of the source (known after the listing). +/// Bytes of the files done. +/// Bytes of all the files. +/// The file being read, relative to the source. +/// Counts by outcome so far (analysis). +/// Files copied or moved so far (copy). +/// When this snapshot was taken. +public sealed record ImportProgress( + long RunId, + ImportPhase Phase, + int FilesDone, + int FilesTotal, + long BytesDone, + long BytesTotal, + string? CurrentFile, + IReadOnlyDictionary Outcomes, + int Copied, + DateTimeOffset UpdatedAt) +{ + /// Done fraction between 0 and 1 (by bytes when known, else by files). + public double Fraction => BytesTotal > 0 ? Math.Clamp((double)BytesDone / BytesTotal, 0, 1) + : FilesTotal > 0 ? Math.Clamp((double)FilesDone / FilesTotal, 0, 1) : 0; +} + +/// Where the files of a source folder go (the «Va in» menu of mockup 09). +public enum FolderTargetKind +{ + /// «Scegli un account…»: the folder's files stay out of the import. + None, + + /// An account already in Febe. + Existing, + + /// «Nuovo account, solo archivio»: created when the copy starts. + NewArchiveAccount, +} + +/// The association of a source folder. +/// None, existing account or new «Solo archivio» account. +/// The existing account. +/// The account's user name (existing or to create). +public sealed record FolderTarget(FolderTargetKind Kind, long? AccountId = null, string? Username = null) +{ + public static FolderTarget None { get; } = new(FolderTargetKind.None); + + public static FolderTarget Existing(long accountId) => new(FolderTargetKind.Existing, accountId); + + public static FolderTarget NewArchiveAccount(string username) => new(FolderTargetKind.NewArchiveAccount, null, username); +} + +/// A row of the «Cartelle e account» table (mockup 09). +/// Folder relative to the source ('' for the source itself): the key to pass back. +/// Name shown («marta.demo», «Foto sparse»). +/// Account guessed from the name, when it can be a user name. +/// Files of the folder. +/// Their size. +/// «Nuovi». +/// «Già presenti» (identical copies in the source included). +/// «Doppioni probabili». +/// «Non riconosciuti». +/// Files whose Instagram identifier or code is known. +/// Where the folder goes. +public sealed record ImportFolderReview( + string Folder, + string DisplayName, + string? ProbableAccount, + int Files, + long Bytes, + int New, + int AlreadyInLibrary, + int ProbableDuplicates, + int Unrecognized, + int Recognized, + FolderTarget Target) +{ + /// The folder has no account: its files stay out (spec §9.4). + public bool IsBlocked => Target.Kind == FolderTargetKind.None; +} + +/// The summary at the top of step 3 (mockup 09). +/// The import. +/// The source as shown. +/// Files of the source. +/// Their size. +/// Counts per outcome. +/// Files whose identifier or code is known: Febe will not download them again (§9.5). +/// Probable duplicates still waiting for a decision. +/// The folders with their association. +/// From the start of the import to the end of the analysis. +/// The 4K Stogram hypothesis recognizer was used. +/// Files already copied or moved by this import. +public sealed record ImportReviewSummary( + ImportRun Run, + string DisplayPath, + int Files, + long Bytes, + IReadOnlyDictionary ByOutcome, + int Recognized, + int PendingDuplicates, + IReadOnlyList Folders, + TimeSpan? AnalysisDuration, + bool StogramHypothesis, + int Copied) +{ + /// «Sposta» is offered only for writable sources. + public bool CanMove => !Run.SourceReadOnly; + + /// The line under the title: «12.480 file, 38 GB, analizzati in 18 minuti. Nessun file è stato ancora copiato.» + public string Headline => ImportText.Headline(Files, Bytes, AnalysisDuration, Copied); +} + +/// One side of a probable duplicate, as the comparison panel shows it. +/// A library file («In libreria»); otherwise a file of the source («Da importare»). +/// The library file. +/// The file of the source. +/// Account of the library file, or destination of the source file. +/// Path relative to the account folder (library) or to the source. +/// Photo or video. +/// Width in pixels. +/// Height in pixels. +/// Size. +/// Publication (library) or found date (source). +/// SHA-256: the library thumbnail key. +/// A library thumbnail exists for . +public sealed record DuplicateSide( + bool InLibrary, + long? MediaId, + long? ImportFileId, + string? Username, + string? Path, + MediaKind? Kind, + int? Width, + int? Height, + long? Bytes, + DateTimeOffset? Date, + string? Sha256, + bool HasThumbnail); + +/// A probable duplicate to decide (right panel of mockup 09). No choice is made in advance. +/// The stored pair (its is Pending until Alberto chooses). +/// The file already there (library, or the first file met in the source). +/// The file of the source. +/// The «Più grande» badge goes on the candidate (more pixels, then more bytes). +public sealed record DuplicateCase(DuplicatePair Pair, DuplicateSide Existing, DuplicateSide Candidate, bool CandidateIsLarger) +{ + /// Both sides are files of the source (a duplicate inside the source itself). + public bool InsideSource => !Existing.InLibrary; +} + +/// What «Importa» would do now (the final button and the line next to it). +/// Files that will be copied (replacements included). +/// Of those, files that replace a smaller library file («Tieni il più grande»). +/// Files that will not be copied: already in the library, not recognized, decided against. +/// Files that stay out because their folder has no account. +/// Folders without account that hold files to import. +/// Files that wait for a decision on a probable duplicate. +/// Files already copied or moved by this import. +/// Size of the files to import. +/// Copia or Sposta. +public sealed record ImportPlan( + int ToImport, + int ToReplace, + int Skipped, + int LeftOutNoAccount, + int FoldersWithoutAccount, + int LeftOutUndecided, + int AlreadyDone, + long Bytes, + ImportMode Mode) +{ + /// The final button: «Importa 7.682 file». + public string ButtonLabel => ImportText.ImportButton(ToImport); + + /// The line next to it: «1 cartella senza account: 1.438 file restano fuori», or null. + public string? LeftOutLabel => ImportText.LeftOut(FoldersWithoutAccount, LeftOutNoAccount, LeftOutUndecided); +} + +/// Which pending pairs a decision applies to (the «Fai lo stesso per gli altri» box of mockup 09). +public enum DecisionScope +{ + /// Only this pair. + ThisPair, + + /// Every pair of this import still waiting, with the same reason (same identifier, or visually similar). + SameReason, + + /// Every pair of this import still waiting. + AllPending, +} diff --git a/src/Febe.Core/Import/ImportPlanner.cs b/src/Febe.Core/Import/ImportPlanner.cs new file mode 100644 index 0000000..bf3dbe8 --- /dev/null +++ b/src/Febe.Core/Import/ImportPlanner.cs @@ -0,0 +1,255 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Import; + +/// What the copy does with one file. +internal enum PlannedAction +{ + /// Already copied, moved or skipped by this import. + Done, + + /// Not analysed (or unreadable): the copy ignores it. + NotAnalyzed, + + /// Copied into the destination account. + Import, + + /// Replaces a smaller library file: Alberto chose «Tieni il più grande» (rule 12). + Replace, + + /// Not copied: already in the library, not a photo or video, or decided against. + Skip, + + /// Stays out: the folder has no account. + WaitNoAccount, + + /// Stays out: a probable duplicate waits for Alberto's decision. + WaitDecision, +} + +/// The planned action for a file, with the note for the report. +internal sealed record PlannedFile(ImportFile File, PlannedAction Action, string? Note, long? ReplaceMediaId); + +/// +/// Decides, from outcomes, folder associations and Alberto's decisions on probable duplicates, what the copy does with +/// each file. The same rules give the plan shown before the copy («Importa 7.682 file») and drive the copy itself. +/// +/// «Già in libreria» and «Non riconosciuto» are skipped; a copy identical to an earlier file of the source is copied +/// only if its twin did not enter the library (checked again at copy time); +/// a file with a pair still waiting for a decision stays out, and so does the other file of a pair inside the +/// source; +/// «Tieni quello in libreria»: the source file is skipped. «Tienili entrambi»: it is imported. «Tieni il più grande»: +/// if the library file is larger the source file is skipped, otherwise it replaces the library file (more pixels win, +/// then more bytes; a tie keeps the library file). Inside the source, among files joined by «tieni il più grande» only +/// the largest is imported; +/// files of a folder without account stay out. +/// +/// +internal sealed class ImportPlanner +{ + private readonly Dictionary> _pairsByFile = []; + private readonly Dictionary _decided = []; + private readonly Dictionary _replacements = []; + private readonly IReadOnlyDictionary _newAccounts; + + private ImportPlanner(IReadOnlyDictionary newAccounts) => _newAccounts = newAccounts; + + /// Loads pairs, sizes and the folders going to new accounts. + public static async Task LoadAsync(IFebeStorage storage, long runId, IReadOnlyDictionary files, CancellationToken ct) + { + var planner = new ImportPlanner(await ImportRunSettings.GetNewAccountsAsync(storage.Settings, runId, ct).ConfigureAwait(false)); + var pairs = new List(); + long after = 0; + while (true) + { + var page = await storage.Imports.ListPairsAsync(runId, pendingOnly: false, after, 5000, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + pairs.AddRange(page); + after = page[^1].Id; + } + + foreach (var pair in pairs) + { + foreach (var id in new[] { pair.CandidateImportFileId, pair.ExistingImportFileId }.OfType()) + { + if (!planner._pairsByFile.TryGetValue(id, out var list)) + { + list = []; + planner._pairsByFile[id] = list; + } + + list.Add(pair); + } + } + + var groups = new UnionFind(); + foreach (var pair in pairs.Where(p => p.Decision != DuplicateDecision.Pending && p.CandidateImportFileId is not null)) + { + var candidate = pair.CandidateImportFileId!.Value; + if (pair.ExistingMediaId is { } mediaId) + { + switch (pair.Decision) + { + case DuplicateDecision.KeepExisting: + planner.Lose(candidate, ImportText.NoteKeptExisting); + break; + case DuplicateDecision.KeepLarger: + var library = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false); + if (library is not null && files.TryGetValue(candidate, out var file) + && IsLarger(file.Width, file.Height, file.Bytes, library.Width, library.Height, library.Bytes)) + { + planner._replacements[candidate] = mediaId; + } + else + { + planner.Lose(candidate, ImportText.NoteLibraryLarger); + } + + break; + default: + break; // KeepBoth: imported + } + } + else if (pair.ExistingImportFileId is { } existing) + { + switch (pair.Decision) + { + case DuplicateDecision.KeepExisting: + planner.Lose(candidate, ImportText.NoteKeptOtherInSource); + break; + case DuplicateDecision.KeepLarger: + groups.Union(existing, candidate); + break; + default: + break; + } + } + } + + foreach (var group in groups.Groups()) + { + var members = group.Where(files.ContainsKey).Select(id => files[id]).ToList(); + var winner = members + .OrderByDescending(f => (long)(f.Width ?? 0) * (f.Height ?? 0)) + .ThenByDescending(f => f.Bytes) + .ThenBy(f => f.Id) + .FirstOrDefault(); + foreach (var member in members.Where(m => m.Id != winner?.Id)) + { + planner.Lose(member.Id, ImportText.NoteKeptOtherInSource); + } + } + + return planner; + } + + /// True when the folder of the file has (or will have) an account. + public bool HasTarget(ImportFile file) => file.TargetAccountId is not null || _newAccounts.ContainsKey(file.Folder); + + public PlannedFile Classify(ImportFile file) + { + ArgumentNullException.ThrowIfNull(file); + switch (file.State) + { + case ImportFileState.Copied or ImportFileState.Moved or ImportFileState.Skipped: + return new PlannedFile(file, PlannedAction.Done, null, null); + case ImportFileState.Pending: + case ImportFileState.Failed when file.Outcome == ImportOutcome.Pending: + return new PlannedFile(file, PlannedAction.NotAnalyzed, file.LastError, null); + default: + break; + } + + switch (file.Outcome) + { + case ImportOutcome.Unrecognized: + return new PlannedFile(file, PlannedAction.Skip, ImportText.NoteNotRecognized, null); + case ImportOutcome.AlreadyInLibrary: + return new PlannedFile(file, PlannedAction.Skip, file.LastError ?? ImportText.NoteAlreadyInLibrary, null); + case ImportOutcome.Pending: + return new PlannedFile(file, PlannedAction.NotAnalyzed, file.LastError, null); + default: + break; + } + + if (_pairsByFile.TryGetValue(file.Id, out var pairs) && pairs.Exists(p => p.Decision == DuplicateDecision.Pending)) + { + return new PlannedFile(file, PlannedAction.WaitDecision, ImportText.NoteUndecided, null); + } + + if (_decided.TryGetValue(file.Id, out var decided)) + { + return new PlannedFile(file, decided.Action, decided.Note, null); + } + + if (!HasTarget(file)) + { + return new PlannedFile(file, PlannedAction.WaitNoAccount, ImportText.NoteNoAccount, null); + } + + return _replacements.TryGetValue(file.Id, out var mediaId) + ? new PlannedFile(file, PlannedAction.Replace, ImportText.NoteReplaced, mediaId) + : new PlannedFile(file, PlannedAction.Import, null, null); + } + + /// + /// True when the first file is larger than the second: more pixels when both sizes are known and differ, otherwise + /// more bytes. A tie is not larger. + /// + public static bool IsLarger(int? width, int? height, long? bytes, int? otherWidth, int? otherHeight, long? otherBytes) + { + if (width is { } w && height is { } h && otherWidth is { } ow && otherHeight is { } oh && (long)w * h != (long)ow * oh) + { + return (long)w * h > (long)ow * oh; + } + + return (bytes ?? 0) > (otherBytes ?? 0); + } + + private void Lose(long fileId, string note) + { + _decided.TryAdd(fileId, (PlannedAction.Skip, note)); + _replacements.Remove(fileId); + } + + private sealed class UnionFind + { + private readonly Dictionary _parent = []; + + public void Union(long a, long b) + { + var ra = Find(a); + var rb = Find(b); + if (ra != rb) + { + _parent[Math.Max(ra, rb)] = Math.Min(ra, rb); + } + } + + public IEnumerable> Groups() => + _parent.Keys.ToList().GroupBy(Find).Select(g => (IReadOnlyList)g.ToList()); + + private long Find(long x) + { + if (!_parent.TryGetValue(x, out var parent)) + { + _parent[x] = x; + return x; + } + + if (parent == x) + { + return x; + } + + var root = Find(parent); + _parent[x] = root; + return root; + } + } +} diff --git a/src/Febe.Core/Import/ImportPreview.cs b/src/Febe.Core/Import/ImportPreview.cs new file mode 100644 index 0000000..5b699c9 --- /dev/null +++ b/src/Febe.Core/Import/ImportPreview.cs @@ -0,0 +1,34 @@ +using Febe.Core.Library; +using SkiaSharp; + +namespace Febe.Core.Import; + +/// In-memory previews of source photos for the comparison panel (nothing is written to disk). +internal static class ImportPreview +{ + private const int JpegQuality = 82; + + /// A JPEG of the image, upright, at most pixels; null when it cannot be decoded. + public static byte[]? RenderJpeg(Stream encodedImage, int longSide) + { + using var bitmap = ImageDecoding.DecodeUpright(encodedImage, longSide); + if (bitmap is null) + { + return null; + } + + var scale = Math.Min(1.0, (double)longSide / Math.Max(bitmap.Width, bitmap.Height)); + var width = Math.Max(1, (int)Math.Round(bitmap.Width * scale)); + var height = Math.Max(1, (int)Math.Round(bitmap.Height * scale)); + using var surface = SKSurface.Create(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul)); + surface.Canvas.Clear(SKColors.White); + using (var image = SKImage.FromBitmap(bitmap)) + { + surface.Canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null); + } + + using var snapshot = surface.Snapshot(); + using var data = snapshot.Encode(SKEncodedImageFormat.Jpeg, JpegQuality); + return data?.ToArray(); + } +} diff --git a/src/Febe.Core/Import/ImportReports.cs b/src/Febe.Core/Import/ImportReports.cs new file mode 100644 index 0000000..6b2cac9 --- /dev/null +++ b/src/Febe.Core/Import/ImportReports.cs @@ -0,0 +1,213 @@ +using System.Globalization; +using System.Text; +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Import; + +/// How many files of an import concern an account. +public sealed record AccountCount(string Username, int Files); + +/// A file of the report with its note. +public sealed record ReportNote(string Path, string Note); + +/// The final report of an import, on screen (spec §9.4 «resoconto a schermo»). +/// The import. +/// The source as shown. +/// Files of the source. +/// Their size. +/// Counts per outcome of the analysis. +/// Counts per state now. +/// Copied into the library (moved included). +/// Of those, originals deleted after verification («Sposta»). +/// Of those, files that replaced a smaller library file. +/// Not copied: already in the library, not recognized, decided against. +/// Still out: folder without account or duplicate without decision. +/// Not succeeded (unreadable, changed, copy not verified). +/// Size of the copied files. +/// Copied files per destination account. +/// Where the «Già in libreria» files already are. +/// The files that are neither photos nor videos (at most ). +/// Files that failed or need attention, with the reason (at most ). +public sealed record ImportReport( + ImportRun Run, + string DisplayPath, + int Files, + long Bytes, + IReadOnlyDictionary ByOutcome, + IReadOnlyDictionary ByState, + int Copied, + int Moved, + int Replaced, + int Skipped, + int LeftOut, + int Failed, + long BytesCopied, + IReadOnlyList ImportedByAccount, + IReadOnlyList AlreadyInLibraryByAccount, + IReadOnlyList Unrecognized, + IReadOnlyList Problems); + +/// +/// The report of an import and its CSV export (spec §9.4, §4.8): one row per file, ';' as separator, UTF-8 with BOM, so +/// that it opens well in Excel in Italian. +/// +public sealed class ImportReports(ImportEnvironment env) +{ + /// The longest lists of the on-screen report (the CSV has every file). + public const int MaxListed = 200; + + private static readonly string[] Header = + [ + "File", "Cartella", "Esito", "Stato", "Account di destinazione", "Tipo", "Data", "Origine della data", "Formato", "Byte", + "Larghezza", "Altezza", "Durata (s)", "SHA-256", "Codice", "Identificativo Instagram", "Già in libreria", "Destinazione", "Nota", + ]; + + public async Task GetReportAsync(long runId, CancellationToken ct = default) + { + var run = await env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Importazione {runId} non trovata."); + var summary = await env.Storage.Imports.GetSummaryAsync(runId, ct).ConfigureAwait(false); + int replaced = 0; + long bytesCopied = 0; + var imported = new Dictionary(StringComparer.OrdinalIgnoreCase); + var already = new Dictionary(StringComparer.OrdinalIgnoreCase); + var unrecognized = new List(); + var problems = new List(); + await foreach (var row in RowsAsync(runId, ct).ConfigureAwait(false)) + { + var file = row.File; + if (file.State is ImportFileState.Copied or ImportFileState.Moved) + { + bytesCopied += file.Bytes; + var isReplacement = file.LastError?.StartsWith(ImportText.NoteReplaced, StringComparison.Ordinal) == true; + replaced += isReplacement ? 1 : 0; + var user = (isReplacement ? row.MatchedUsername : row.TargetUsername) ?? "?"; + imported[user] = imported.GetValueOrDefault(user) + 1; + } + + if (file.Outcome == ImportOutcome.AlreadyInLibrary && row.MatchedUsername is { } where) + { + already[where] = already.GetValueOrDefault(where) + 1; + } + + if (file.Outcome == ImportOutcome.Unrecognized && unrecognized.Count < MaxListed) + { + unrecognized.Add(file.RelativePath); + } + + if ((file.State == ImportFileState.Failed || (file.State == ImportFileState.Copied && file.LastError is { } attention && !attention.StartsWith(ImportText.NoteReplaced, StringComparison.Ordinal))) + && problems.Count < MaxListed) + { + problems.Add(new ReportNote(file.RelativePath, file.LastError ?? "Non riuscito.")); + } + } + + return new ImportReport( + run, + env.CreateSources().DisplayPath(run.SourcePath), + summary.Total, + summary.Bytes, + summary.ByOutcome, + summary.ByState, + summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved], + summary.ByState[ImportFileState.Moved], + replaced, + summary.ByState[ImportFileState.Skipped], + summary.ByState[ImportFileState.Analyzed], + summary.ByState[ImportFileState.Failed], + bytesCopied, + Sorted(imported), + Sorted(already), + unrecognized, + problems); + } + + /// Suggested name of the CSV file: «importazione-2026-10-13-12.csv». + public string CsvFileName(ImportRun run) + { + ArgumentNullException.ThrowIfNull(run); + var day = LocalCalendar.ToLocal(run.StartedAt, env.Clock.LocalZone); + return string.Create(CultureInfo.InvariantCulture, $"importazione-{day:yyyy-MM-dd}-{run.Id}.csv"); + } + + /// Writes one row per file to (left open): ';', UTF-8 with BOM, CRLF. + public async Task WriteCsvAsync(long runId, Stream destination, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(destination); + var zone = env.Clock.LocalZone; + await using var writer = new StreamWriter(destination, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true), 64 * 1024, leaveOpen: true) { NewLine = "\r\n" }; + await writer.WriteLineAsync(Line(Header)).ConfigureAwait(false); + await foreach (var row in RowsAsync(runId, ct).ConfigureAwait(false)) + { + var f = row.File; + var replaced = f.LastError?.StartsWith(ImportText.NoteReplaced, StringComparison.Ordinal) == true; + var destinationUser = replaced ? row.MatchedUsername : row.TargetUsername; + await writer.WriteLineAsync(Line( + [ + f.RelativePath, + f.Folder, + ImportText.Outcome(f.Outcome), + ImportText.State(f.State), + destinationUser ?? string.Empty, + ImportText.Kind(f.ProbableKind), + f.TakenAt is { } taken ? LocalCalendar.ToLocal(taken, zone).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) : string.Empty, + ImportText.DateSource(f.DateSource), + f.ContentType ?? string.Empty, + f.Bytes.ToString(CultureInfo.InvariantCulture), + f.Width?.ToString(CultureInfo.InvariantCulture) ?? string.Empty, + f.Height?.ToString(CultureInfo.InvariantCulture) ?? string.Empty, + f.Duration is { } d ? Engine.ItalianText.Decimal(d.TotalSeconds, 1, keepZeros: true).Replace(".", string.Empty, StringComparison.Ordinal) : string.Empty, + f.Sha256 ?? string.Empty, + f.Code ?? string.Empty, + f.InstagramId ?? string.Empty, + row.MatchedUsername is { } user ? $"{user}/{row.MatchedPath}" : string.Empty, + f.DestinationPath is { } path && destinationUser is { } to ? $"{to}/{path}" : f.DestinationPath ?? string.Empty, + f.LastError ?? string.Empty, + ])).ConfigureAwait(false); + } + + await writer.FlushAsync(ct).ConfigureAwait(false); + } + + /// A CSV line: fields separated by ';', quoted when needed. + internal static string Line(IReadOnlyList fields) => string.Join(';', fields.Select(Field)); + + /// + /// One field: quoted when it holds ';', '"', a line break or outer spaces; a text that Excel would take for a formula + /// (starting with = + - @) gets a leading apostrophe. + /// + internal static string Field(string value) + { + if (value.Length > 0 && value[0] is '=' or '+' or '-' or '@' or '\t' or '\r') + { + value = "'" + value; + } + + var quote = value.AsSpan().IndexOfAny(";\"\r\n") >= 0 || (value.Length > 0 && (char.IsWhiteSpace(value[0]) || char.IsWhiteSpace(value[^1]))); + return quote ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value; + } + + private async IAsyncEnumerable RowsAsync(long runId, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct) + { + long after = 0; + while (true) + { + var page = await env.Storage.Imports.ListReportRowsAsync(runId, after, 2000, ct).ConfigureAwait(false); + if (page.Count == 0) + { + yield break; + } + + foreach (var row in page) + { + yield return row; + } + + after = page[^1].File.Id; + } + } + + private static List Sorted(Dictionary counts) => + counts.OrderByDescending(c => c.Value).ThenBy(c => c.Key, StringComparer.Ordinal).Select(c => new AccountCount(c.Key, c.Value)).ToList(); +} diff --git a/src/Febe.Core/Import/ImportReview.cs b/src/Febe.Core/Import/ImportReview.cs new file mode 100644 index 0000000..b7bb3ad --- /dev/null +++ b/src/Febe.Core/Import/ImportReview.cs @@ -0,0 +1,400 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Import; + +/// +/// Step 3 of the import (spec §9.3, §9.4, mockup 09): the summary, the association of folders with accounts, the probable +/// duplicates and Alberto's decisions, the mode and the plan of the final button. Nothing here touches a file. +/// +public sealed class ImportReview(ImportEnvironment env) +{ + private readonly SemaphoreSlim _settingsGate = new(1, 1); + + /// The summary of an analysed import. + public async Task GetSummaryAsync(long runId, CancellationToken ct = default) + { + var run = await GetRunAsync(runId, ct).ConfigureAwait(false); + var summary = await env.Storage.Imports.GetSummaryAsync(runId, ct).ConfigureAwait(false); + var folders = await ListFoldersAsync(run, ct).ConfigureAwait(false); + var pending = await env.Storage.Imports.CountPairsAsync(runId, pendingOnly: true, ct).ConfigureAwait(false); + var stogram = await ImportRunSettings.GetStogramAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false); + return new ImportReviewSummary( + run, + env.CreateSources().DisplayPath(run.SourcePath), + summary.Total, + summary.Bytes, + summary.ByOutcome, + folders.Sum(f => f.Recognized), + pending, + folders, + run.AnalyzedAt is { } analyzed ? analyzed - run.StartedAt : null, + stogram, + summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved]); + } + + /// The rows of «Cartelle e account». + public async Task> ListFoldersAsync(long runId, CancellationToken ct = default) => + await ListFoldersAsync(await GetRunAsync(runId, ct).ConfigureAwait(false), ct).ConfigureAwait(false); + + private async Task> ListFoldersAsync(ImportRun run, CancellationToken ct) + { + var counts = await env.Storage.Imports.ListFolderCountsAsync(run.Id, ct).ConfigureAwait(false); + var newAccounts = await ImportRunSettings.GetNewAccountsAsync(env.Storage.Settings, run.Id, ct).ConfigureAwait(false); + var layout = Directory.Exists(run.SourcePath) ? SourceLayout.Inspect(run.SourcePath) : null; + var rows = new List(); + foreach (var folder in counts) + { + FolderTarget target; + if (folder.TargetAccountId is { } accountId) + { + var account = await env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false); + target = new FolderTarget(FolderTargetKind.Existing, accountId, account?.Username); + } + else if (newAccounts.TryGetValue(folder.Folder, out var username)) + { + target = FolderTarget.NewArchiveAccount(username); + } + else + { + target = FolderTarget.None; + } + + rows.Add(new ImportFolderReview( + folder.Folder, + layout?.DisplayName(folder.Folder) ?? (folder.Folder.Length == 0 ? Path.GetFileName(run.SourcePath) : folder.Folder), + folder.ProbableAccount, + folder.Files, + folder.Bytes, + folder.ByOutcome[ImportOutcome.New], + folder.ByOutcome[ImportOutcome.AlreadyInLibrary] + folder.ByOutcome[ImportOutcome.IdenticalInSource], + folder.ByOutcome[ImportOutcome.ProbableDuplicate], + folder.ByOutcome[ImportOutcome.Unrecognized], + folder.Recognized, + target)); + } + + return rows; + } + + /// + /// Associates a source folder («Va in»): an existing account, a new «Solo archivio» account (created when the copy + /// starts; an existing account with that name is used instead), or none (its files stay out). + /// + /// The account does not exist or the name cannot be an Instagram user name. + public async Task SetFolderTargetAsync(long runId, string folder, FolderTarget target, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(folder); + ArgumentNullException.ThrowIfNull(target); + var run = await GetRunAsync(runId, ct).ConfigureAwait(false); + EnsureEditable(run); + if (!(await env.Storage.Imports.ListFolderCountsAsync(runId, ct).ConfigureAwait(false)).Any(f => f.Folder == folder)) + { + throw new ArgumentException("Questa cartella non fa parte dell'importazione.", nameof(folder)); + } + + long? accountId = null; + string? newUsername = null; + switch (target.Kind) + { + case FolderTargetKind.Existing: + var account = target.AccountId is { } id ? await env.Storage.Accounts.GetAsync(id, ct).ConfigureAwait(false) : null; + accountId = account?.Id ?? throw new ArgumentException("L'account scelto non esiste più: scegline un altro.", nameof(target)); + break; + case FolderTargetKind.NewArchiveAccount: + var username = SourceLayout.UsernameFrom(target.Username) + ?? throw new ArgumentException("Il nome dell'account può contenere solo lettere, numeri, punti e trattini bassi, fino a 30 caratteri.", nameof(target)); + if (await env.Storage.Accounts.FindByUsernameAsync(username, ct).ConfigureAwait(false) is { } existing) + { + accountId = existing.Id; + } + else + { + newUsername = username; + } + + break; + default: + break; + } + + await _settingsGate.WaitAsync(ct).ConfigureAwait(false); + try + { + var intents = new Dictionary(await ImportRunSettings.GetNewAccountsAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false), StringComparer.Ordinal); + var changed = newUsername is null ? intents.Remove(folder) : !intents.TryGetValue(folder, out var old) || old != newUsername; + if (newUsername is not null) + { + intents[folder] = newUsername; + } + + await env.Storage.Imports.SetFolderTargetAsync(runId, folder, accountId, ct).ConfigureAwait(false); + if (changed) + { + await ImportRunSettings.SetNewAccountsAsync(env.Storage.Settings, runId, intents, ct).ConfigureAwait(false); + } + } + finally + { + _settingsGate.Release(); + } + } + + /// «Copia» or «Sposta». + /// «Sposta» on a read-only source. + public async Task SetModeAsync(long runId, ImportMode mode, CancellationToken ct = default) + { + var run = await GetRunAsync(runId, ct).ConfigureAwait(false); + EnsureEditable(run); + if (mode == ImportMode.Move && run.SourceReadOnly) + { + throw new InvalidOperationException("La sorgente è in sola lettura: si può solo copiare."); + } + + run = run with { Mode = mode }; + await env.Storage.Imports.UpdateRunAsync(run, ct).ConfigureAwait(false); + return run; + } + + /// + /// The probable duplicates of an import, both sides described, in creation order. + /// gives the ones still to decide. + /// + public async Task> ListDuplicatesAsync(long runId, bool pendingOnly = true, long afterPairId = 0, int limit = 50, CancellationToken ct = default) + { + var pairs = await env.Storage.Imports.ListPairsAsync(runId, pendingOnly, afterPairId, limit, ct).ConfigureAwait(false); + var cases = new List(pairs.Count); + foreach (var pair in pairs) + { + cases.Add(await DescribeAsync(pair, ct).ConfigureAwait(false)); + } + + return cases; + } + + /// One probable duplicate, both sides described. + public async Task GetDuplicateAsync(long pairId, CancellationToken ct = default) => + await env.Storage.Duplicates.GetAsync(pairId, ct).ConfigureAwait(false) is { Origin: DuplicateOrigin.Import } pair + ? await DescribeAsync(pair, ct).ConfigureAwait(false) + : null; + + /// + /// Records Alberto's decision on a probable duplicate and, with , on the other pairs of the + /// same import still waiting («Fai lo stesso per gli altri»). Nothing is copied or replaced here: the copy applies + /// the decisions. Returns how many pairs were decided. + /// + /// The decision is «Pending», or the pair is not of this import. + public async Task DecideAsync(long runId, long pairId, DuplicateDecision decision, DecisionScope scope = DecisionScope.ThisPair, CancellationToken ct = default) + { + if (decision == DuplicateDecision.Pending) + { + throw new ArgumentException("Scegli una delle tre possibilità.", nameof(decision)); + } + + var run = await GetRunAsync(runId, ct).ConfigureAwait(false); + EnsureEditable(run); + var pair = await env.Storage.Duplicates.GetAsync(pairId, ct).ConfigureAwait(false); + var candidate = pair?.CandidateImportFileId is { } fileId ? await env.Storage.Imports.GetFileAsync(fileId, ct).ConfigureAwait(false) : null; + if (pair is null || candidate?.RunId != runId) + { + throw new ArgumentException("Questa coppia non appartiene all'importazione.", nameof(pairId)); + } + + var targets = new List { pair }; + if (scope != DecisionScope.ThisPair) + { + long after = 0; + while (true) + { + var page = await env.Storage.Imports.ListPairsAsync(runId, pendingOnly: true, after, 1000, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + targets.AddRange(page.Where(p => p.Id != pair.Id && (scope == DecisionScope.AllPending || p.Reason == pair.Reason))); + after = page[^1].Id; + } + } + + var now = env.Clock.Now; + var fileDecision = decision switch + { + DuplicateDecision.KeepLarger => ImportDecision.KeepLarger, + DuplicateDecision.KeepExisting => ImportDecision.KeepExisting, + _ => ImportDecision.KeepBoth, + }; + foreach (var target in targets) + { + await env.Storage.Duplicates.DecideAsync(target.Id, decision, now, ct).ConfigureAwait(false); + if (target.CandidateImportFileId is { } id && await env.Storage.Imports.GetFileAsync(id, ct).ConfigureAwait(false) is { } file) + { + await env.Storage.Imports.UpdateFileAsync(file with { Decision = fileDecision }, ct).ConfigureAwait(false); + } + } + + return targets.Count; + } + + /// Takes back a decision: the pair waits again (no choice made). + public async Task UndecideAsync(long runId, long pairId, CancellationToken ct = default) + { + var run = await GetRunAsync(runId, ct).ConfigureAwait(false); + EnsureEditable(run); + var pair = await env.Storage.Duplicates.GetAsync(pairId, ct).ConfigureAwait(false) + ?? throw new ArgumentException("Coppia non trovata.", nameof(pairId)); + await env.Storage.Duplicates.DecideAsync(pair.Id, DuplicateDecision.Pending, env.Clock.Now, ct).ConfigureAwait(false); + if (pair.CandidateImportFileId is { } id && await env.Storage.Imports.GetFileAsync(id, ct).ConfigureAwait(false) is { RunId: var r } file && r == runId) + { + await env.Storage.Imports.UpdateFileAsync(file with { Decision = ImportDecision.None }, ct).ConfigureAwait(false); + } + } + + /// What «Importa» would do now: files to import, to replace, skipped, left out and why. + public async Task GetPlanAsync(long runId, CancellationToken ct = default) + { + var run = await GetRunAsync(runId, ct).ConfigureAwait(false); + var files = new Dictionary(); + long after = 0; + while (true) + { + var page = await env.Storage.Imports.ListFilesAsync(new ImportFileQuery { RunId = runId, AfterId = after, Limit = 10_000 }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + foreach (var file in page) + { + files[file.Id] = file; + } + + after = page[^1].Id; + } + + var planner = await ImportPlanner.LoadAsync(env.Storage, runId, files, ct).ConfigureAwait(false); + int import = 0, replace = 0, skipped = 0, noAccount = 0, undecided = 0, done = 0; + long bytes = 0; + var blockedFolders = new HashSet(StringComparer.Ordinal); + foreach (var file in files.Values) + { + var planned = planner.Classify(file); + switch (planned.Action) + { + case PlannedAction.Import: + import++; + bytes += file.Bytes; + break; + case PlannedAction.Replace: + import++; + replace++; + bytes += file.Bytes; + break; + case PlannedAction.Skip: + skipped++; + break; + case PlannedAction.WaitNoAccount: + noAccount++; + blockedFolders.Add(file.Folder); + break; + case PlannedAction.WaitDecision: + undecided++; + break; + case PlannedAction.Done: + if (file.State is ImportFileState.Copied or ImportFileState.Moved) + { + done++; + } + else + { + skipped++; + } + + break; + default: + break; + } + } + + return new ImportPlan(import, replace, skipped, noAccount, blockedFolders.Count, undecided, done, bytes, run.Mode); + } + + /// Opens a file of the source for reading (the comparison panel shows it). + public async Task OpenSourceFileAsync(long fileId, CancellationToken ct = default) + { + var (run, file) = await GetFileWithRunAsync(fileId, ct).ConfigureAwait(false); + return env.FileSystem.OpenRead(LibraryLayout.FullPath(run.SourcePath, file.RelativePath)); + } + + /// + /// A JPEG preview of a photo of the source, at most pixels (not stored: the source file + /// may never enter the library). Null for videos and formats that cannot be decoded. + /// + public async Task RenderPreviewAsync(long fileId, int longSide = ThumbnailStore.LongSide, CancellationToken ct = default) + { + var (run, file) = await GetFileWithRunAsync(fileId, ct).ConfigureAwait(false); + if (file.MediaKind != MediaKind.Photo) + { + return null; + } + + await using var stream = env.FileSystem.OpenRead(LibraryLayout.FullPath(run.SourcePath, file.RelativePath)); + return ImportPreview.RenderJpeg(stream, Math.Clamp(longSide, 64, 2048)); + } + + private async Task<(ImportRun Run, ImportFile File)> GetFileWithRunAsync(long fileId, CancellationToken ct) + { + var file = await env.Storage.Imports.GetFileAsync(fileId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"File di importazione {fileId} non trovato."); + return (await GetRunAsync(file.RunId, ct).ConfigureAwait(false), file); + } + + private async Task DescribeAsync(DuplicatePair pair, CancellationToken ct) + { + var existing = await SideAsync(pair.ExistingMediaId, pair.ExistingImportFileId, ct).ConfigureAwait(false); + var candidate = await SideAsync(pair.CandidateMediaId, pair.CandidateImportFileId, ct).ConfigureAwait(false); + var larger = ImportPlanner.IsLarger(candidate.Width, candidate.Height, candidate.Bytes, existing.Width, existing.Height, existing.Bytes); + return new DuplicateCase(pair, existing, candidate, larger); + } + + private async Task SideAsync(long? mediaId, long? fileId, CancellationToken ct) + { + if (mediaId is { } m && await env.Storage.Media.GetAsync(m, ct).ConfigureAwait(false) is { } media) + { + var entry = await env.Storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false); + var account = entry is null ? null : await env.Storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false); + return new DuplicateSide(true, media.Id, null, account?.Username, media.RelativePath, media.Kind, media.Width, media.Height, media.Bytes, entry?.PublishedAt, media.Sha256, media.HasThumbnail); + } + + if (fileId is { } f && await env.Storage.Imports.GetFileAsync(f, ct).ConfigureAwait(false) is { } file) + { + var account = file.TargetAccountId is { } a ? await env.Storage.Accounts.GetAsync(a, ct).ConfigureAwait(false) : null; + return new DuplicateSide(false, null, file.Id, account?.Username ?? file.ProbableAccount, file.RelativePath, file.MediaKind, file.Width, file.Height, file.Bytes, file.TakenAt, file.Sha256, false); + } + + return new DuplicateSide(mediaId is not null, mediaId, fileId, null, null, null, null, null, null, null, null, false); + } + + private async Task GetRunAsync(long runId, CancellationToken ct) => + await env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Importazione {runId} non trovata."); + + private static void EnsureEditable(ImportRun run) + { + if (run.State is ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted) + { + throw new InvalidOperationException("L'analisi non è finita: le scelte si fanno dopo."); + } + + if (run.State is ImportRunState.Copying) + { + throw new InvalidOperationException("La copia è in corso: interrompila prima di cambiare le scelte."); + } + + if (run.State is ImportRunState.Cancelled) + { + throw new InvalidOperationException("Questa importazione è stata annullata."); + } + } +} diff --git a/src/Febe.Core/Import/ImportService.cs b/src/Febe.Core/Import/ImportService.cs new file mode 100644 index 0000000..0c17708 --- /dev/null +++ b/src/Febe.Core/Import/ImportService.cs @@ -0,0 +1,362 @@ +using System.Diagnostics; +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Import; + +/// +/// The import for the interface (spec §9, mockup 09): one object with the four steps. Analysis and copy run in the +/// background, one job at a time; the interface follows them with or +/// and stops them with . Every state lives in the database: +/// after a restart call once, then continues where it stopped. +/// See src/Febe.Core/Import/LEGGIMI.md. +/// +public sealed class ImportService : IAsyncDisposable +{ + private static readonly TimeSpan ProgressInterval = TimeSpan.FromMilliseconds(250); + + private readonly ImportEnvironment _env; + private readonly Lock _gate = new(); + private Job? _job; + private ImportProgress? _current; + private long _lastPublished; + + public ImportService(ImportEnvironment env) + { + ArgumentNullException.ThrowIfNull(env); + _env = env; + Sources = env.CreateSources(); + Analyzer = new ImportAnalyzer(env); + Copier = new ImportCopier(env); + Review = new ImportReview(env); + Reports = new ImportReports(env); + } + + /// + /// Progress of the running job, at most four times a second and at every change of phase. Raised on a pool thread: + /// handlers must be quick and thread-safe. + /// + public event EventHandler? ProgressChanged; + + /// Step 1: checking sources. + public ImportSources Sources { get; } + + public ImportAnalyzer Analyzer { get; } + + public ImportCopier Copier { get; } + + public ImportReview Review { get; } + + public ImportReports Reports { get; } + + /// The import whose job is running, if any. + public long? ActiveRunId + { + get + { + lock (_gate) + { + return _job is { Task.IsCompleted: false } job ? job.RunId : null; + } + } + } + + /// The last error of a background job that could not be stored with the import (normally null). + public string? LastJobError { get; private set; } + + /// + /// After a restart: an analysis or a copy that was running when Febe stopped becomes «interrotta», ready to resume. + /// Call once at start-up, before anything else. + /// + public async Task RecoverAsync(CancellationToken ct = default) + { + var active = ActiveRunId; + var recovered = 0; + foreach (var run in await _env.Storage.Imports.ListRunsAsync(ct).ConfigureAwait(false)) + { + if (run.Id == active) + { + continue; + } + + var state = run.State switch + { + ImportRunState.Analyzing => ImportRunState.AnalysisInterrupted, + ImportRunState.Copying => ImportRunState.CopyInterrupted, + _ => run.State, + }; + if (state != run.State) + { + await _env.Storage.Imports.UpdateRunAsync(run with { State = state }, ct).ConfigureAwait(false); + recovered++; + } + } + + return recovered; + } + + /// Imports, newest first (to offer «Riprendi» on an unfinished one). + public Task> ListRunsAsync(CancellationToken ct = default) => _env.Storage.Imports.ListRunsAsync(ct); + + public Task GetRunAsync(long runId, CancellationToken ct = default) => _env.Storage.Imports.GetRunAsync(runId, ct); + + /// Step 1: checks a folder. Throws with the reason in Italian. + public ImportSourceInfo InspectSource(string path) => Sources.Inspect(path); + + /// Step 1 in Docker: the subfolders of /importa (or of one of its subfolders). + public IReadOnlyList BrowseSources(string? path = null) => Sources.Browse(path); + + /// Step 1 → 2: records the import and starts the analysis in the background. + /// The folder cannot be used. + /// Another import job is running. + public async Task StartAsync(string sourcePath, ImportAnalysisOptions? options = null, CancellationToken ct = default) + { + EnsureIdle(); + var source = Sources.Inspect(sourcePath); + var run = await Analyzer.CreateRunAsync(source, options, ct).ConfigureAwait(false); + StartJob(run.Id, ImportPhase.Analyzing, (progress, token) => Analyzer.AnalyzeAsync(run.Id, progress, token)); + return run; + } + + /// Continues an interrupted analysis or copy in the background. + public async Task ResumeAsync(long runId, CancellationToken ct = default) + { + var run = await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Importazione {runId} non trovata."); + switch (run.State) + { + case ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted: + StartJob(runId, ImportPhase.Analyzing, (progress, token) => Analyzer.AnalyzeAsync(runId, progress, token)); + break; + case ImportRunState.Copying or ImportRunState.CopyInterrupted: + StartJob(runId, ImportPhase.Copying, (progress, token) => Copier.CopyAsync(runId, progress, token)); + break; + default: + throw new InvalidOperationException("Questa importazione non è interrotta: non c'è niente da riprendere."); + } + + return run; + } + + /// + /// Step 3 → 4: starts the copy in the background (also «importa i rimasti» on a completed import, after a change of + /// associations or decisions). With the mode is set first. + /// + public async Task StartCopyAsync(long runId, ImportMode? mode = null, CancellationToken ct = default) + { + EnsureIdle(); + var run = mode is { } m + ? await Review.SetModeAsync(runId, m, ct).ConfigureAwait(false) + : await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Importazione {runId} non trovata."); + if (run.State is not (ImportRunState.Reviewing or ImportRunState.CopyInterrupted or ImportRunState.Completed)) + { + throw new InvalidOperationException("L'analisi non è finita: riprendila prima di importare."); + } + + StartJob(runId, ImportPhase.Copying, (progress, token) => Copier.CopyAsync(runId, progress, token)); + return run; + } + + /// «Interrompi»: stops the running job of this import and waits until its state is saved. + public async Task InterruptAsync(long runId) + { + Job? job; + lock (_gate) + { + job = _job is { RunId: var id } j && id == runId ? j : null; + } + + if (job is null) + { + return; + } + + await job.Cancellation.CancelAsync().ConfigureAwait(false); + await job.Task.ConfigureAwait(false); + } + + /// Waits for the running job of this import (if any) to end, however it ends; returns the import. + public async Task WaitAsync(long runId, CancellationToken ct = default) + { + Job? job; + lock (_gate) + { + job = _job is { RunId: var id } j && id == runId ? j : null; + } + + if (job is not null) + { + await job.Task.WaitAsync(ct).ConfigureAwait(false); + } + + return await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false); + } + + /// The progress of an import: live while its job runs, otherwise from the database. + public async Task GetProgressAsync(long runId) + { + lock (_gate) + { + if (_job is { RunId: var id, Task.IsCompleted: false } && id == runId && _current is { } current && current.RunId == runId) + { + return current; + } + } + + var run = await _env.Storage.Imports.GetRunAsync(runId).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Importazione {runId} non trovata."); + var phase = run.State switch + { + ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted => ImportPhase.Analyzing, + ImportRunState.Copying or ImportRunState.CopyInterrupted => ImportPhase.Copying, + _ => ImportPhase.Finished, + }; + return await Analyzer.SnapshotAsync(runId, phase, null).ConfigureAwait(false); + } + + // Step 3, delegated to the review (see ImportReview). + public Task GetReviewAsync(long runId, CancellationToken ct = default) => Review.GetSummaryAsync(runId, ct); + + public Task SetFolderTargetAsync(long runId, string folder, FolderTarget target, CancellationToken ct = default) => Review.SetFolderTargetAsync(runId, folder, target, ct); + + public Task SetModeAsync(long runId, ImportMode mode, CancellationToken ct = default) => Review.SetModeAsync(runId, mode, ct); + + public Task> ListDuplicatesAsync(long runId, bool pendingOnly = true, long afterPairId = 0, int limit = 50, CancellationToken ct = default) => + Review.ListDuplicatesAsync(runId, pendingOnly, afterPairId, limit, ct); + + public Task DecideAsync(long runId, long pairId, DuplicateDecision decision, DecisionScope scope = DecisionScope.ThisPair, CancellationToken ct = default) => + Review.DecideAsync(runId, pairId, decision, scope, ct); + + public Task GetPlanAsync(long runId, CancellationToken ct = default) => Review.GetPlanAsync(runId, ct); + + // Step 4. + public Task GetReportAsync(long runId, CancellationToken ct = default) => Reports.GetReportAsync(runId, ct); + + public Task WriteCsvAsync(long runId, Stream destination, CancellationToken ct = default) => Reports.WriteCsvAsync(runId, destination, ct); + + /// + /// «Annulla l'importazione»: stops its job; if nothing was copied yet the import disappears with its records, + /// otherwise it becomes «annullata» and its pending duplicates are withdrawn. Files are never touched. + /// + public async Task DiscardAsync(long runId, CancellationToken ct = default) + { + await InterruptAsync(runId).ConfigureAwait(false); + var run = await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false); + if (run is null) + { + return; + } + + var summary = await _env.Storage.Imports.GetSummaryAsync(runId, ct).ConfigureAwait(false); + if (summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved] == 0) + { + await _env.Storage.Imports.DeleteRunAsync(runId, ct).ConfigureAwait(false); + } + else + { + await _env.Storage.Imports.RemovePendingPairsAsync(runId, ct).ConfigureAwait(false); + await _env.Storage.Imports.UpdateRunAsync(run with { State = ImportRunState.Cancelled, CompletedAt = _env.Clock.Now }, ct).ConfigureAwait(false); + } + + await ImportRunSettings.ClearAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false); + } + + public async ValueTask DisposeAsync() + { + Job? job; + lock (_gate) + { + job = _job; + } + + if (job is not null) + { + await job.Cancellation.CancelAsync().ConfigureAwait(false); + await job.Task.ConfigureAwait(false); + job.Cancellation.Dispose(); + } + } + + private void EnsureIdle() + { + if (ActiveRunId is not null) + { + throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila."); + } + } + + private void StartJob(long runId, ImportPhase phase, Func, CancellationToken, Task> work) + { + lock (_gate) + { + if (_job is { Task.IsCompleted: false }) + { + throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila."); + } + + _job?.Cancellation.Dispose(); + var cancellation = new CancellationTokenSource(); + var reporter = new Reporter(this); + _current = new ImportProgress(runId, phase, 0, 0, 0, 0, null, new Dictionary(), 0, _env.Clock.Now); + var task = Task.Run(async () => + { + try + { + await work(reporter, cancellation.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellation.IsCancellationRequested) + { + // Interrupted: the state was saved by the analysis or the copy. + } + catch (Exception ex) + { + LastJobError = ImportAnalyzer.ErrorText(ex); // also stored with the import when possible + } + finally + { + try + { + Publish(await Analyzer.SnapshotAsync(runId, ImportPhase.Finished, null).ConfigureAwait(false), force: true); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // The database is closing: nothing to publish. + } + } + }); + _job = new Job(runId, phase, cancellation, task); + } + } + + private void Publish(ImportProgress progress, bool force) + { + lock (_gate) + { + _current = progress; + } + + var now = Stopwatch.GetTimestamp(); + var last = Interlocked.Read(ref _lastPublished); + if (!force && Stopwatch.GetElapsedTime(last, now) < ProgressInterval) + { + return; + } + + Interlocked.Exchange(ref _lastPublished, now); + ProgressChanged?.Invoke(this, progress); + } + + private sealed record Job(long RunId, ImportPhase Phase, CancellationTokenSource Cancellation, Task Task); + + private sealed class Reporter(ImportService owner) : IProgress + { + private ImportPhase? _phase; + + public void Report(ImportProgress value) + { + var phaseChanged = _phase != value.Phase; + _phase = value.Phase; + owner.Publish(value, phaseChanged); + } + } +} diff --git a/src/Febe.Core/Import/ImportSources.cs b/src/Febe.Core/Import/ImportSources.cs new file mode 100644 index 0000000..7e7ea86 --- /dev/null +++ b/src/Febe.Core/Import/ImportSources.cs @@ -0,0 +1,373 @@ +using Febe.Core.Library; + +namespace Febe.Core.Import; + +/// Where sources may be chosen (spec §9.1 «Sorgente», §11). +public sealed record ImportSourceOptions +{ + /// + /// Root of the sources. In Docker the volume /importa: a source is that folder or one of its subfolders. + /// Null on Windows: any folder Alberto chooses. + /// + public string? Root { get; init; } + + /// + /// The root is mounted read-only (the /importa volume, spec §11): «Sposta» is never offered below it, whatever + /// the mount table says. + /// + public bool RootIsReadOnly { get; init; } + + /// Docker: sources under , read-only. + public static ImportSourceOptions Docker(string root = "/importa") => new() { Root = root, RootIsReadOnly = true }; + + /// Windows (and development): any folder. + public static ImportSourceOptions AnyFolder { get; } = new(); +} + +/// What step 1 knows about a chosen source. +/// Full path of the folder. +/// Path shown to Alberto (relative to the root in Docker, e.g. «/importa/4K Stogram»). +/// Folder name. +/// The source cannot be written: «Sposta» does not appear (spec §9.4). +/// Account folders with _febe.jsonl were found. +/// +/// A 4K Stogram database file is present (only its existence is checked): the interface may offer the hypothesis +/// recognizer, saying it is unverified. +/// +/// The folder itself looks like one account (see ). +/// First-level subfolders. +public sealed record ImportSourceInfo( + string FullPath, + string DisplayPath, + string Name, + bool ReadOnly, + bool LooksLikeFebeLibrary, + bool LooksLikeStogram, + bool RootIsAccount, + IReadOnlyList Folders) +{ + /// «Sposta» is offered only for writable sources. + public bool CanMove => !ReadOnly; +} + +/// A folder offered by the source picker (Docker: below /importa). +/// Folder name. +/// Path to pass back to (relative to the root when there is one). +/// The folder has subfolders to open. +public sealed record SourceFolderChoice(string Name, string Path, bool HasSubfolders); + +/// A source that cannot be used; the message (Italian) says why and what to do. +public sealed class ImportSourceException : Exception +{ + public ImportSourceException() + { + } + + public ImportSourceException(string message) + : base(message) + { + } + + public ImportSourceException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// Tells whether a folder can be written, without writing into it. +public interface ISourceAccessProbe +{ + bool IsReadOnly(string fullPath); +} + +/// +/// Read-only detection that never writes into the source: on Linux the mount options of the file system that holds the +/// folder (ro, as for a Docker volume mounted with :ro); on Windows optical drives. A folder that is +/// writable for the system but not for Febe is not detected: there «Sposta» stays offered and an original that cannot be +/// deleted stays where it is (the report says so). +/// +public sealed class SystemSourceAccessProbe(Func? readMounts = null) : ISourceAccessProbe +{ + private readonly Func _readMounts = readMounts ?? ReadProcMounts; + + public bool IsReadOnly(string fullPath) + { + ArgumentException.ThrowIfNullOrWhiteSpace(fullPath); + if (OperatingSystem.IsWindows()) + { + try + { + var root = Path.GetPathRoot(Path.GetFullPath(fullPath)); + return !string.IsNullOrEmpty(root) && new DriveInfo(root).DriveType == DriveType.CDRom; + } + catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException) + { + return false; + } + } + + var content = _readMounts(); + return content is not null && MountIsReadOnly(content, Path.GetFullPath(fullPath)); + } + + /// True when the mount that contains has the ro option. + public static bool MountIsReadOnly(string mountTable, string fullPath) + { + ArgumentNullException.ThrowIfNull(mountTable); + string? bestPoint = null; + var readOnly = false; + foreach (var raw in mountTable.Split('\n')) + { + var fields = raw.Trim().Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries); + if (fields.Length < 4) + { + continue; + } + + var point = MountTable.Unescape(fields[1]); + var trimmed = point.Length > 1 ? point.TrimEnd('/') : point; + var contains = trimmed == "/" || fullPath == trimmed || fullPath.StartsWith(trimmed + "/", StringComparison.Ordinal); + if (contains && (bestPoint is null || trimmed.Length >= bestPoint.Length)) + { + bestPoint = trimmed; + readOnly = fields[3].Split(',').Contains("ro", StringComparer.Ordinal); + } + } + + return readOnly; + } + + private static string? ReadProcMounts() + { + try + { + if (File.Exists("/proc/self/mounts")) + { + return File.ReadAllText("/proc/self/mounts"); + } + + return File.Exists("/proc/mounts") ? File.ReadAllText("/proc/mounts") : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } +} + +/// +/// Step 1 of the import (spec §9.1): checks a chosen folder and tells whether it is read-only. Never writes into the +/// source. A source may not be, contain or sit inside the Data folder, contain the library, or sit inside an account +/// folder of the library (folders of the library without _febe.jsonl may be imported, as the rebuild suggests). +/// +public sealed class ImportSources +{ + private static readonly StringComparison PathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + private static readonly HashSet IgnoredNames = new(StringComparer.OrdinalIgnoreCase) + { + AccountJournal.FileName, "Thumbs.db", "desktop.ini", ".DS_Store", "stogram.sqlite", "stogram.app.sqlite", "stogram.sqlite.backup", + "stogram.sqlite-wal", "stogram.sqlite-shm", "stogram.app.sqlite-wal", "stogram.app.sqlite-shm", + }; + + private readonly ImportSourceOptions _options; + private readonly ISourceAccessProbe _probe; + private readonly string? _libraryRoot; + private readonly string? _dataRoot; + + /// Root and read-only flag. + /// The library folder (a source may not contain it). + /// The Data folder (a source may not overlap it). + /// Read-only detection; by default. + public ImportSources(ImportSourceOptions options, string? libraryRoot = null, string? dataRoot = null, ISourceAccessProbe? probe = null) + { + ArgumentNullException.ThrowIfNull(options); + _options = options; + _probe = probe ?? new SystemSourceAccessProbe(); + _libraryRoot = libraryRoot is null ? null : Trim(Path.GetFullPath(libraryRoot)); + _dataRoot = dataRoot is null ? null : Trim(Path.GetFullPath(dataRoot)); + Root = options.Root is null ? null : Trim(Path.GetFullPath(options.Root)); + } + + /// Full path of the root of the sources (Docker), or null (any folder). + public string? Root { get; } + + /// Enumeration used everywhere on sources: hidden, system files and links are skipped. + public static EnumerationOptions Enumeration(bool recursive) => new() + { + RecurseSubdirectories = recursive, + IgnoreInaccessible = true, + AttributesToSkip = FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReparsePoint, + ReturnSpecialDirectories = false, + MatchType = MatchType.Simple, + }; + + /// + /// Files that are not content and are not listed at all: Febe's journal, its temporary files, the 4K Stogram + /// databases, Windows and macOS housekeeping files. + /// + public static bool IsIgnoredFile(string fileName) + { + ArgumentNullException.ThrowIfNull(fileName); + return IgnoredNames.Contains(fileName) || SafeFileWriter.IsTemporaryFile(fileName) || fileName.StartsWith("._", StringComparison.Ordinal); + } + + /// The full path of a chosen folder, checked. + /// The folder cannot be used; the message says why. + public string Resolve(string chosen) + { + if (string.IsNullOrWhiteSpace(chosen)) + { + throw new ImportSourceException("Scegli la cartella da importare."); + } + + if (Root is null && !Path.IsPathFullyQualified(chosen)) + { + throw new ImportSourceException("Scegli la cartella con il suo percorso completo."); + } + + string full; + try + { + full = Trim(Root is { } root && !Path.IsPathFullyQualified(chosen) + ? Path.GetFullPath(Path.Combine(root, chosen.TrimStart('/', '\\'))) + : Path.GetFullPath(chosen)); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + throw new ImportSourceException("Il percorso scelto non è valido: scegli di nuovo la cartella.", ex); + } + + if (Root is { } r && !IsSameOrInside(full, r)) + { + throw new ImportSourceException($"In Docker si importa solo da {r} o da una sua sottocartella: monta la cartella da importare in quel volume."); + } + + if (!Directory.Exists(full)) + { + throw new ImportSourceException(File.Exists(full) + ? "Hai scelto un file: scegli la cartella che lo contiene." + : $"La cartella {full} non esiste più: controlla che il disco sia collegato e sceglila di nuovo."); + } + + if (Root is not null && new DirectoryInfo(full).LinkTarget is not null) + { + throw new ImportSourceException("La cartella scelta è un collegamento: scegli la cartella a cui punta."); + } + + if (_dataRoot is { } data && (IsSameOrInside(full, data) || IsSameOrInside(data, full))) + { + throw new ImportSourceException("La cartella scelta contiene la cartella dei dati di Febe o ne fa parte: scegli la cartella con le foto e i video da importare."); + } + + if (_libraryRoot is { } library) + { + if (IsSameOrInside(library, full)) + { + throw new ImportSourceException("La cartella scelta contiene la libreria di Febe: scegli una cartella fuori dalla libreria."); + } + + if (IsSameOrInside(full, library) && InsideAccountFolder(full, library)) + { + throw new ImportSourceException("La cartella scelta è la cartella di un account della libreria: i suoi file sono già in libreria."); + } + } + + return full; + } + + /// Checks a chosen folder and tells what it looks like (step 1). + /// The folder cannot be used. + public ImportSourceInfo Inspect(string chosen) + { + var full = Resolve(chosen); + var layout = SourceLayout.Inspect(full); + var looksLikeFebe = layout.UnitFolders.Any(f => File.Exists(AccountJournal.PathFor(layout.FolderPath(f)))); + var looksLikeStogram = StogramHypothesisRecognizer.LooksLikeStogramFolder(full) + || layout.FirstLevelFolders.Take(200).Any(f => StogramHypothesisRecognizer.LooksLikeStogramFolder(Path.Combine(full, f))); + return new ImportSourceInfo(full, DisplayPath(full), layout.RootName, IsReadOnly(full), looksLikeFebe, looksLikeStogram, layout.RootIsAccount, layout.FirstLevelFolders); + } + + /// True when the folder cannot be written (configured read-only root, or the system says so). + public bool IsReadOnly(string fullPath) + { + ArgumentException.ThrowIfNullOrWhiteSpace(fullPath); + var full = Trim(Path.GetFullPath(fullPath)); + return (_options.RootIsReadOnly && Root is { } root && IsSameOrInside(full, root)) || _probe.IsReadOnly(full); + } + + /// + /// Subfolders offered by the picker. With a root (Docker) is relative to it and the result + /// paths are relative too; without a root it is an absolute folder. + /// + public IReadOnlyList Browse(string? path = null) + { + string folder; + if (Root is { } root) + { + folder = string.IsNullOrWhiteSpace(path) ? root : Trim(Path.GetFullPath(Path.Combine(root, path.TrimStart('/', '\\')))); + if (!IsSameOrInside(folder, root)) + { + throw new ImportSourceException($"Si sfoglia solo dentro {root}."); + } + } + else if (string.IsNullOrWhiteSpace(path)) + { + throw new ImportSourceException("Scegli la cartella da sfogliare."); + } + else + { + folder = Trim(Path.GetFullPath(path)); + } + + if (!Directory.Exists(folder)) + { + throw new ImportSourceException($"La cartella {folder} non esiste."); + } + + return Directory.EnumerateDirectories(folder, "*", Enumeration(recursive: false)) + .Order(StringComparer.Ordinal) + .Select(d => new SourceFolderChoice( + Path.GetFileName(d), + Root is { } r ? LibraryLayout.ToStored(Path.GetRelativePath(r, d)) : d, + Directory.EnumerateDirectories(d, "*", Enumeration(recursive: false)).Any())) + .ToList(); + } + + /// The path shown to Alberto: in Docker relative to the root, with the root's name in front. + public string DisplayPath(string fullPath) + { + if (Root is { } root && IsSameOrInside(fullPath, root)) + { + var relative = Path.GetRelativePath(root, fullPath); + return relative == "." ? root : LibraryLayout.ToStored(Path.Combine(root, relative)); + } + + return fullPath; + } + + private static bool InsideAccountFolder(string full, string library) + { + for (var folder = full; folder is not null && IsSameOrInside(folder, library) && !Same(folder, library); folder = Path.GetDirectoryName(folder)) + { + if (File.Exists(AccountJournal.PathFor(folder))) + { + return true; + } + } + + return false; + } + + private static bool Same(string a, string b) => string.Equals(Trim(a), Trim(b), PathComparison); + + private static bool IsSameOrInside(string path, string folder) + { + var p = Trim(path); + var f = Trim(folder); + return string.Equals(p, f, PathComparison) + || p.StartsWith(f.EndsWith(Path.DirectorySeparatorChar) ? f : f + Path.DirectorySeparatorChar, PathComparison); + } + + private static string Trim(string path) => path.Length > 1 ? Path.TrimEndingDirectorySeparator(path) : path; +} diff --git a/src/Febe.Core/Import/ImportText.cs b/src/Febe.Core/Import/ImportText.cs new file mode 100644 index 0000000..3dab244 --- /dev/null +++ b/src/Febe.Core/Import/ImportText.cs @@ -0,0 +1,147 @@ +using Febe.Core.Domain; +using Febe.Core.Engine; + +namespace Febe.Core.Import; + +/// +/// Texts of the import for Alberto (spec §10.4): sentence case, dots for thousands, buttons that say what happens. The +/// interface uses these so that the same thing has the same name everywhere (and in the CSV). +/// +public static class ImportText +{ + /// Name of an outcome, as in the four boxes of mockup 09. + public static string Outcome(ImportOutcome outcome) => outcome switch + { + ImportOutcome.Pending => "Da analizzare", + ImportOutcome.New => "Nuovo", + ImportOutcome.AlreadyInLibrary => "Già in libreria", + ImportOutcome.ProbableDuplicate => "Doppione probabile", + ImportOutcome.Unrecognized => "Non riconosciuto", + ImportOutcome.IdenticalInSource => "Copia identica nella sorgente", + _ => outcome.ToString(), + }; + + /// The line under each box of mockup 09. + public static string OutcomeHint(ImportOutcome outcome) => outcome switch + { + ImportOutcome.New => "Non ci sono in libreria", + ImportOutcome.AlreadyInLibrary => "Identici, verranno saltati", + ImportOutcome.ProbableDuplicate => "Stessa immagine, file diverso: decidi tu", + ImportOutcome.Unrecognized => "Né foto né video, ignorati", + ImportOutcome.IdenticalInSource => "Uguali a un altro file della sorgente: si copia una volta sola", + _ => string.Empty, + }; + + /// State of a file. + public static string State(ImportFileState state) => state switch + { + ImportFileState.Pending => "Da analizzare", + ImportFileState.Analyzed => "Analizzato", + ImportFileState.Copied => "Copiato", + ImportFileState.Moved => "Spostato", + ImportFileState.Skipped => "Saltato", + ImportFileState.Failed => "Non riuscito", + _ => state.ToString(), + }; + + /// Where a date came from. + public static string DateSource(ImportDateSource? source) => source switch + { + ImportDateSource.FileName => "Nome del file", + ImportDateSource.Metadata => "Metadati del file", + ImportDateSource.ModifiedTime => "Data di modifica", + ImportDateSource.Journal => "Archivio di Febe (_febe.jsonl)", + _ => string.Empty, + }; + + /// A kind, singular, for tables. + public static string Kind(EntryKind? kind) => kind switch + { + EntryKind.Post => "Post", + EntryKind.Story => "Storia", + EntryKind.Highlight => "In evidenza", + EntryKind.Tagged => "Taggato", + EntryKind.ProfilePicture => "Foto del profilo", + _ => string.Empty, + }; + + /// The three choices of the comparison panel. + public static string Decision(DuplicateDecision decision) => decision switch + { + DuplicateDecision.KeepLarger => "Tieni il più grande e scarta l'altro", + DuplicateDecision.KeepExisting => "Tieni quello già in libreria", + DuplicateDecision.KeepBoth => "Tienili entrambi", + _ => "Da decidere", + }; + + /// «Copia» or «Sposta». + public static string Mode(ImportMode mode) => mode == ImportMode.Move ? "Sposta" : "Copia"; + + /// The line next to the mode switch. + public static string ModeHint(ImportMode mode) => mode == ImportMode.Move + ? "Gli originali si eliminano solo dopo aver verificato la copia." + : "Gli originali restano dove sono."; + + /// «Importa 7.682 file». + public static string ImportButton(int files) => "Importa " + ItalianText.Number(files) + " file"; + + /// «1 cartella senza account: 1.438 file restano fuori», with the files waiting for a decision; null when nothing stays out. + public static string? LeftOut(int foldersWithoutAccount, int filesWithoutAccount, int undecided) + { + var parts = new List(); + if (filesWithoutAccount > 0) + { + var folders = foldersWithoutAccount == 1 ? "1 cartella senza account" : ItalianText.Number(foldersWithoutAccount) + " cartelle senza account"; + parts.Add(folders + ": " + Files(filesWithoutAccount) + (filesWithoutAccount == 1 ? " resta fuori" : " restano fuori")); + } + + if (undecided > 0) + { + parts.Add(Files(undecided) + (undecided == 1 ? " aspetta" : " aspettano") + " la tua decisione sui doppioni probabili"); + } + + return parts.Count == 0 ? null : string.Join("; ", parts); + } + + /// «12.480 file, 38 GB, analizzati in 18 minuti. Nessun file è stato ancora copiato.» + public static string Headline(int files, long bytes, TimeSpan? analysis, int copied) + { + var text = Files(files) + ", " + ItalianText.Bytes(bytes); + if (analysis is { } duration) + { + text += ", analizzati in " + ItalianText.Duration(duration); + } + + text += ". "; + text += copied switch + { + 0 => "Nessun file è stato ancora copiato.", + 1 => "1 file è già stato copiato.", + _ => ItalianText.Number(copied) + " file sono già stati copiati.", + }; + return text; + } + + /// «1 file importato», «7.682 file importati»: the number with the right ending. + public static string Count(int count, string one, string many) => + count == 1 ? "1 " + one : ItalianText.Number(count) + " " + many; + + /// «1 file», «1.438 file». + public static string Files(int count) => ItalianText.Number(count) + " file"; + + // Notes stored with a file (import_file.last_error) and shown in the report. + internal const string NoteDeletedByAlberto = "L'avevi eliminato dalla libreria ricordando la scelta: non viene reimportato."; + internal const string NoteNoAccount = "La cartella non è associata a un account: il file resta fuori."; + internal const string NoteUndecided = "Doppione probabile in attesa della tua decisione: il file resta fuori."; + internal const string NoteKeptExisting = "Hai scelto di tenere il file già in libreria."; + internal const string NoteLibraryLarger = "Hai scelto di tenere il più grande: è quello già in libreria."; + internal const string NoteKeptOtherInSource = "Hai scelto di tenere l'altro file della sorgente."; + internal const string NoteNotRecognized = "Né foto né video: ignorato."; + internal const string NoteAlreadyInLibrary = "Identico a un file già in libreria: saltato."; + internal const string NoteReplaced = "Ha sostituito il file più piccolo della libreria, come hai scelto."; + internal const string NoteChanged = "Il file è cambiato dopo l'analisi: non è stato copiato. Per prenderlo avvia una nuova importazione della cartella."; + internal const string NoteNotVerified = "La copia in libreria non corrisponde all'originale: l'originale resta al suo posto. Controlla il disco della libreria."; + internal const string NoteOriginalKept = "Copiato; l'originale non si è potuto eliminare e resta al suo posto."; + internal const string NoteMovePending = "Copiato; l'originale si elimina dopo la verifica della copia."; + internal const string NoteOldNotDeleted = "Il file sostituito non si è potuto eliminare dalla libreria: resta accanto al nuovo."; +} diff --git a/src/Febe.Core/Import/LEGGIMI.md b/src/Febe.Core/Import/LEGGIMI.md new file mode 100644 index 0000000..3ed596b --- /dev/null +++ b/src/Febe.Core/Import/LEGGIMI.md @@ -0,0 +1,170 @@ +# Importazione (tappa M7) + +Questa cartella contiene il motore dell'importazione della specifica §9: sorgente, analisi, revisione, copia. Non c'è +interfaccia: le pagine del mockup 09 si costruiscono sopra `ImportService`. Tutto ciò che Alberto legge è in italiano +(`ImportText`), il codice è in inglese. + +## Come si monta + +`ImportService` riceve un `ImportEnvironment` con gli stessi oggetti della libreria usati dalla raccolta, così miniature, +impronte e righe di `_febe.jsonl` nascono nello stesso modo. + +```csharp +var settings = await LibrarySettings.LoadAsync(storage.Settings, defaultLibraryRoot); +var layout = new LibraryLayout(settings.LibraryRoot); +var import = new ImportService(new ImportEnvironment +{ + Storage = storage, // FebeDatabase.OpenAsync(...) + Layout = layout, + Naming = settings.Naming, + Journal = new AccountJournal(clock), + Clock = clock, + Thumbnails = new ThumbnailStore(data.Thumbnails), + HashIndex = sharedHashIndex, // lo stesso PerceptualHashIndex della raccolta + Frames = VideoFrameExtractor.TryCreate(), // miniature dei video importati, se c'è ffmpeg + VideoProbe = FfprobeVideoMetadataProbe.TryCreate(), // facoltativo + SetFileTimeToPublication = settings.SetFileTimeToPublication, + Sources = isDocker ? ImportSourceOptions.Docker("/importa") : ImportSourceOptions.AnyFolder, + DataFolder = data.Root, +}); +await import.RecoverAsync(); // una volta all'avvio: ciò che era «in corso» diventa «interrotto» +``` + +- In Docker la radice delle sorgenti è `/importa` (configurabile: `ImportSourceOptions.Docker(radice)`) ed è in sola + lettura per configurazione: «Sposta» non compare mai lì sotto. +- Su Windows `ImportSourceOptions.AnyFolder`: la cartella la sceglie Alberto con la finestra nativa e arriva come + percorso completo. +- Un solo lavoro (analisi o copia) alla volta per servizio. Gli stati stanno nel database: un riavvio non perde nulla. + +## I quattro passi e l'API + +| Passo | Metodi di `ImportService` | Note | +|---|---|---| +| 1 Sorgente | `BrowseSources(percorso?)`, `InspectSource(percorso)` | `ImportSourceException` con il motivo in italiano. `ImportSourceInfo.CanMove`, `LooksLikeFebeLibrary`, `LooksLikeStogram` | +| 2 Analisi | `StartAsync(percorso, opzioni)`, `ResumeAsync(id)`, `InterruptAsync(id)`, `GetProgressAsync(id)`, evento `ProgressChanged`, `WaitAsync(id)` | Sola lettura. Interrompibile e ripristinabile | +| 3 Revisione | `GetReviewAsync(id)`, `SetFolderTargetAsync(id, cartella, FolderTarget)`, `ListDuplicatesAsync(id)`, `DecideAsync(id, coppia, scelta, DecisionScope)`, `SetModeAsync(id, Copia/Sposta)`, `GetPlanAsync(id)` | Nessun file viene toccato. Più metodi in `service.Review` (`UndecideAsync`, `GetDuplicateAsync`, `RenderPreviewAsync`, `OpenSourceFileAsync`, `ListFoldersAsync`) | +| 4 Copia | `StartCopyAsync(id, modo?)`, `GetReportAsync(id)`, `WriteCsvAsync(id, stream)`, `Reports.CsvFileName(run)` | La copia si può rilanciare sulla stessa importazione: prende i file rimasti fuori | +| Altro | `ListRunsAsync()`, `GetRunAsync(id)`, `DiscardAsync(id)` | «Annulla»: se nulla è stato copiato l'importazione sparisce, altrimenti diventa «annullata». Mai un file toccato | + +Testi pronti per i pulsanti e le righe del mockup: `ImportPlan.ButtonLabel` («Importa 7.682 file»), +`ImportPlan.LeftOutLabel` («1 cartella senza account: 1.438 file restano fuori»), `ImportReviewSummary.Headline`, +`ImportText.Outcome`, `OutcomeHint`, `Decision`, `Mode`, `ModeHint`, `State`, `DateSource`, `Kind`. + +`ProgressChanged` arriva da un thread del pool, al massimo quattro volte al secondo e sempre a ogni cambio di fase +(`Listing`, `Analyzing`, `Copying`, `Finished`). Per la barra: `ImportProgress.Fraction`, `FilesDone`/`FilesTotal`, +`BytesDone`/`BytesTotal`, `CurrentFile`, `Outcomes`, `Copied`. Chi arriva dopo legge `GetProgressAsync`. + +Per il pannello dei doppioni: `DuplicateCase.Existing` (in libreria, o il primo file incontrato nella sorgente) e +`Candidate` (da importare), con misure, byte, data e account; `CandidateIsLarger` mette il segno «Più grande». +L'immagine in libreria è la miniatura `ThumbnailStore.PathFor(Existing.Sha256)`; quella da importare si ottiene con +`Review.RenderPreviewAsync(fileId)` (JPEG in memoria, non salvato) oppure `OpenSourceFileAsync`. Nessuna scelta è fatta in +partenza (`DuplicateDecision.Pending`); «Fai lo stesso per gli altri» è `DecisionScope.AllPending` (oppure `SameReason`). + +## Analisi (§9.2) + +Per ogni file, senza scrivere nulla nella sorgente: tipo dal contenuto (`MediaSniffer`: JPEG, PNG, GIF, WebP, HEIC/HEIF, +AVIF, BMP, TIFF e raw, MP4, MOV anche senza `ftyp`, 3GP, WebM/Matroska, AVI, WMV, FLV, MPEG; l'audio M4A non è un +video), byte, SHA-256, dimensioni, impronta visiva a 64 bit per le foto, data, identificativo o codice, account +probabile, tipo probabile e titolo della raccolta. + +- **Data**, nell'ordine: nome del file (o `_febe.jsonl` di una libreria di Febe, data esatta), metadati (EXIF + `DateTimeOriginal` poi `CreateDate` letti a mano in JPEG, TIFF, PNG e WebP; `mvhd` di MP4/MOV letto a mano; ffprobe + solo come aggiunta per gli altri video), data di modifica. Se il nome dà solo il giorno e i metadati hanno un'ora + dello stesso giorno, vince l'ora dei metadati. Le ore senza fuso sono quelle di Alberto (`IClock.LocalZone`). +- **Cartelle** (`SourceLayout`): se la cartella scelta contiene solo cartelle di tipo (post, storie, evidenza, + taggati, anni...) o solo file, è un account; altrimenti ogni sottocartella di primo livello è un'unità da associare a + un account, e i file sciolti in cima stanno nell'unità «» senza account probabile. +- File ignorati del tutto: `_febe.jsonl`, temporanei di Febe, database di 4K Stogram, `Thumbs.db`, `desktop.ini`, + file nascosti e collegamenti. +- Un file illeggibile resta «Non riuscito» e viene riprovato alla ripresa. + +### Riconoscitori + +`IImportRecognizer` (punto di estensione): `FebeRecognizer` (giornale e nomi dello schema predefinito), +`StogramHypothesisRecognizer` (solo se chiesto), `GenericRecognizer` (sempre, per ultimo). I campi mancanti di un +riconoscitore si prendono dal successivo (`FileHints.Merge`). + +> **4K Stogram è un'ipotesi da verificare.** Il riconoscitore legge nomi del tipo +> `AAAA-MM-GG HH.MM.SS _.jpg` (ora locale) e le sottocartelle stories/highlights/tagged, come +> ricordato nella §9.6, ma **non è stato provato su file veri**. È spento per impostazione predefinita +> (`ImportAnalysisOptions.StogramHypothesis`), è provato solo su nomi sintetici e non apre mai `stogram.sqlite` (si +> guarda solo se esiste). Prima di usarlo davvero servono da Alberto una ventina di nomi di file reali e, se è +> d'accordo, lo schema di `stogram.sqlite` (domanda 4 di §16): poi si riscrive il riconoscitore sui dati veri. + +## Confronto con la libreria (§9.3) + +`ImportComparer`, in quest'ordine, una coppia al massimo per file: + +1. stesso SHA-256 di un file presente in qualunque account → **Già in libreria** (prima l'account di destinazione; + l'account e il percorso si leggono nel resoconto). Uno SHA-256 di un elemento eliminato da Alberto «ricordando la + scelta» conta come già in libreria, con la nota: un'importazione non annulla un'eliminazione; +2. stesso SHA-256 di un file già incontrato nella sorgente → **copia identica nella sorgente** + (`ImportOutcome.IdenticalInSource`, nuovo valore): si copia una volta sola. Nel riepilogo per cartella conta tra i + «Già presenti»; +3. stesso identificativo o codice (con la posizione nella serie) e file diverso → **Doppione probabile** + (`SameInstagramId`), prima nell'account di destinazione poi nel resto della libreria; +4. impronta entro `PerceptualHash.DuplicateThreshold` (6) di una foto della libreria → **Doppione probabile** + (`VisuallySimilar`), prima l'account di destinazione; +5. gli stessi due controlli sui file precedenti della sorgente (le coppie puntano sempre al primo file del gruppo); +6. altrimenti **Nuovo**. Né foto né video → **Non riconosciuto**. + +I video si confrontano solo per SHA-256 (e identificativo). L'account di destinazione usato nel confronto è quello +trovato dal nome della cartella (o dall'identificativo dell'account in `_febe.jsonl`): cambiare l'associazione dopo +l'analisi non rifà il confronto. + +## Associazione e copia (§9.4) + +- Associazione iniziale: l'account esistente con quell'identificativo o quel nome; altrimenti un nuovo account «Solo + archivio» col nome della cartella, se può essere un nome utente; altrimenti nessuno («Scegli un account…»). Gli + account nuovi nascono solo quando parte la copia. +- Una cartella senza account blocca solo i propri file; un doppione senza decisione blocca solo sé stesso (e l'altro + file se la coppia è dentro la sorgente). Restano «Analizzato» con la nota: dopo una modifica la copia si rilancia. +- Scelte sui doppioni, applicate solo dalla copia: «Tieni quello in libreria» salta il file; «Tienili entrambi» lo + importa (se l'identificativo e la posizione sono già occupati, come elemento a sé senza identificativo, in + `importati/`); «Tieni il più grande» salta il file se in libreria c'è il più grande (più pixel, poi più byte; a + parità resta quello in libreria), altrimenti **sostituisce il file della libreria**: il nuovo file si scrive accanto + e si verifica con lo SHA-256 rileggendolo dal disco, poi si aggiornano il record e `_febe.jsonl`, solo alla fine si + elimina il vecchio file (e la sua miniatura se non serve più). È l'unico punto in cui l'importazione elimina un file + della libreria, e solo per la scelta esplicita di Alberto (regola 12). Dentro la sorgente, tra file legati da «tieni il + più grande» si importa solo il più grande. +- Nomi: con data (dal nome, dal giornale o dai metadati) e codice o identificativo noti, lo schema della libreria; gli + altri in `{account}/importati/` col nome originale. Mai sovrascrivere: un nome occupato diventa «nome (2).ext». +- Ogni file entra con `LibraryIngest`: provenienza «importato», miniatura, impronta (aggiunta all'indice condiviso), + riga di `_febe.jsonl`. I file di un post con più file (stesso codice, posizioni diverse) diventano un elemento solo; un + file che manca a un elemento già in libreria lo completa. +- «Sposta»: la copia si rilegge dal disco e si confronta con lo SHA-256 dell'analisi; solo se coincide si elimina + l'originale. Mai con una sorgente in sola lettura. Se la copia non coincide, l'originale resta e il file è «Non + riuscito». Se l'eliminazione non riesce (file in uso), l'originale resta e la volta dopo si riprova, sempre dopo una + nuova verifica. I file copiati prima con «Copia» non si eliminano mai passando a «Sposta». I file saltati non si + toccano. +- Il contenuto letto alla copia deve avere lo SHA-256 dell'analisi (`MediaContent.ExpectedSha256`): se il file è + cambiato nel frattempo non entra. + +## Resoconto e CSV + +`GetReportAsync`: conteggi per esito e per stato, copiati, spostati, sostituiti, saltati, rimasti fuori, non riusciti, +importati per account, «già in libreria» per account, elenco dei non riconosciuti e dei problemi (al massimo 200 voci; +il CSV le ha tutte). `WriteCsvAsync`: una riga per file, `;` come separatore, UTF-8 con BOM, righe CRLF, campi tra +virgolette quando serve, apostrofo davanti a un testo che Excel prenderebbe per una formula. + +## Dove stanno le cose + +- `import_run`, `import_file`, `duplicate_pair` (origine `Import`) come da schema 1, senza migrazioni nuove. +- Scelte senza colonna, nella tabella `setting`: `importazione.{id}.ipotesi-stogram` e `importazione.{id}.nuovi-account` + (cartella → nome del nuovo account). +- `import_file.last_error` porta anche le note per il resoconto (perché un file resta fuori, cosa ha fatto la copia). +- Interrogazioni nuove in `IImportStore`: `ListFolderCountsAsync`, `ListPairsAsync`, `CountPairsAsync`, + `ListReportRowsAsync`, `RemovePendingPairsAsync`, `DeleteRunAsync`, `LoadLibraryIdentifiersAsync`, + `FindEntryByCodeAsync`. + +## Limiti noti + +- HEIC/HEIF: si riconoscono, ma SkiaSharp (pacchetto Linux senza dipendenze) non li decodifica: niente dimensioni, + impronta e miniatura, e l'EXIF dentro HEIC non si legge. Contano solo SHA-256, nome e data di modifica. +- La sola lettura si riconosce dalle opzioni di montaggio (Linux, `ro`) o dai dischi ottici (Windows): una cartella + scrivibile per il sistema ma non per Febe non si riconosce; lì «Sposta» lascia l'originale e lo dice. +- La data `mvhd` si legge come UTC, come vuole il formato; alcune fotocamere vi scrivono l'ora locale. +- Se Febe si ferma nell'istante fra la scrittura di un file e il suo record, alla ripresa il file viene riscritto con + «(2)» e il primo resta in libreria non registrato (la ricostruzione lo segnala come file non registrato). +- Le coppie da scaricamento (§9.5, origine `Download`) non hanno ancora una revisione: questa riguarda solo + l'importazione. diff --git a/src/Febe.Core/Import/MediaSniffer.cs b/src/Febe.Core/Import/MediaSniffer.cs new file mode 100644 index 0000000..d7fb2d3 --- /dev/null +++ b/src/Febe.Core/Import/MediaSniffer.cs @@ -0,0 +1,242 @@ +using System.Buffers.Binary; +using System.Text; +using Febe.Core.Domain; + +namespace Febe.Core.Import; + +/// A file type recognized from the content. +/// Photo or video. +/// Media type, e.g. "image/jpeg". +/// Extension used for the library name, with the dot (e.g. ".jpg"). +/// Short format name for the report («JPEG», «MP4», ...). +public sealed record DetectedType(MediaKind Kind, string ContentType, string Extension, string Format) +{ + /// True for the ISO base media family (MP4, MOV, 3GP): creation time and size come from the moov box. + public bool IsIsoMedia => ContentType is "video/mp4" or "video/quicktime" or "video/3gpp" or "video/3gpp2"; +} + +/// +/// Recognizes photos and videos from their first bytes, not from the extension (spec §9.2). Anything else is «Non +/// riconosciuto». Audio-only containers (M4A) are not videos. +/// +public static class MediaSniffer +{ + /// Bytes to read from the start of a file for . + public const int HeadLength = 512; + + private static readonly byte[] PngSignature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + + private static readonly byte[] AsfSignature = [0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11]; + + private static readonly HashSet HeifBrands = new(StringComparer.Ordinal) + { + "heic", "heix", "heim", "heis", "hevc", "hevx", "hevm", "hevs", "mif1", "msf1", "mif2", "MiHE", "MiHB", + }; + + private static readonly HashSet AvifBrands = new(StringComparer.Ordinal) { "avif", "avis" }; + + private static readonly HashSet Mp4Brands = new(StringComparer.Ordinal) + { + "isom", "iso2", "iso3", "iso4", "iso5", "iso6", "iso7", "iso8", "iso9", "mp41", "mp42", "mp71", "avc1", "dash", + "M4V ", "M4VH", "M4VP", "f4v ", "MSNV", "NDAS", "mmp4", "XAVC", "FACE", "kddi", + }; + + private static readonly HashSet ThreeGpBrands = new(StringComparer.Ordinal) + { + "3gp4", "3gp5", "3gp6", "3gp7", "3gs6", "3gs7", "3ge6", "3ge7", "3gg6", + }; + + private static readonly HashSet AudioBrands = new(StringComparer.Ordinal) { "M4A ", "M4B ", "M4P ", "F4A ", "F4B " }; + + /// Top-level atoms that may open a QuickTime file without ftyp (old cameras). + private static readonly HashSet QuickTimeAtoms = new(StringComparer.Ordinal) { "moov", "mdat", "wide", "free", "skip", "pnot" }; + + /// Extensions of raw camera formats built on TIFF: kept as they are in library names. + private static readonly HashSet TiffFamilyExtensions = new(StringComparer.OrdinalIgnoreCase) + { + ".tif", ".tiff", ".dng", ".cr2", ".nef", ".nrw", ".arw", ".srf", ".sr2", ".orf", ".rw2", ".pef", ".raf", ".erf", ".3fr", + }; + + /// The type of a file from its first bytes; null when it is neither a photo nor a video. + /// The first bytes of the file (at least 12; recommended). + /// The file's own extension, used only to name raw camera formats. + public static DetectedType? Detect(ReadOnlySpan head, string? originalExtension = null) + { + if (head.Length < 4) + { + return null; + } + + if (head[0] == 0xFF && head[1] == 0xD8 && head[2] == 0xFF) + { + return new DetectedType(MediaKind.Photo, "image/jpeg", ".jpg", "JPEG"); + } + + if (head.StartsWith(PngSignature)) + { + return new DetectedType(MediaKind.Photo, "image/png", ".png", "PNG"); + } + + if (head.StartsWith("GIF87a"u8) || head.StartsWith("GIF89a"u8)) + { + return new DetectedType(MediaKind.Photo, "image/gif", ".gif", "GIF"); + } + + if (head.Length >= 12 && head.StartsWith("RIFF"u8)) + { + var form = head.Slice(8, 4); + if (form.SequenceEqual("WEBP"u8)) + { + return new DetectedType(MediaKind.Photo, "image/webp", ".webp", "WebP"); + } + + if (form.SequenceEqual("AVI "u8)) + { + return new DetectedType(MediaKind.Video, "video/x-msvideo", ".avi", "AVI"); + } + + return null; + } + + if (head.StartsWith("II*\0"u8) || head.StartsWith("MM\0*"u8)) + { + var extension = originalExtension is { } ext && TiffFamilyExtensions.Contains(ext) ? ext.ToLowerInvariant() : ".tif"; + return new DetectedType(MediaKind.Photo, "image/tiff", extension, "TIFF"); + } + + if (head.Length >= 18 && head[0] == (byte)'B' && head[1] == (byte)'M') + { + var dib = BinaryPrimitives.ReadUInt32LittleEndian(head.Slice(14, 4)); + if (dib is 12 or 40 or 52 or 56 or 64 or 108 or 124) + { + return new DetectedType(MediaKind.Photo, "image/bmp", ".bmp", "BMP"); + } + } + + if (head.Length >= 12 && head.Slice(4, 4).SequenceEqual("ftyp"u8)) + { + return DetectIsoMedia(head); + } + + if (head.Length >= 8 && QuickTimeAtoms.Contains(Ascii(head.Slice(4, 4))) && BinaryPrimitives.ReadUInt32BigEndian(head) is var size && (size == 1 || size >= 8)) + { + return new DetectedType(MediaKind.Video, "video/quicktime", ".mov", "QuickTime"); + } + + if (head[0] == 0x1A && head[1] == 0x45 && head[2] == 0xDF && head[3] == 0xA3) + { + // EBML: the DocType says WebM or Matroska. + return head.IndexOf("webm"u8) >= 0 + ? new DetectedType(MediaKind.Video, "video/webm", ".webm", "WebM") + : new DetectedType(MediaKind.Video, "video/x-matroska", ".mkv", "Matroska"); + } + + if (head.Length >= 16 && head.StartsWith(AsfSignature)) + { + return new DetectedType(MediaKind.Video, "video/x-ms-asf", ".wmv", "WMV"); + } + + if (head.StartsWith("FLV"u8) && head[3] == 0x01) + { + return new DetectedType(MediaKind.Video, "video/x-flv", ".flv", "FLV"); + } + + if (head[0] == 0x00 && head[1] == 0x00 && head[2] == 0x01 && head[3] == 0xBA) + { + return new DetectedType(MediaKind.Video, "video/mpeg", ".mpg", "MPEG"); + } + + return null; + } + + /// Reads the first bytes of a file (read-only) and detects its type. + public static DetectedType? DetectFile(string path) + { + Span head = stackalloc byte[HeadLength]; + int read; + using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 4096)) + { + read = stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false); + } + + return Detect(head[..read], Path.GetExtension(path)); + } + + private static DetectedType? DetectIsoMedia(ReadOnlySpan head) + { + var boxSize = (int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(head), (uint)head.Length); + var brands = new List { Ascii(head.Slice(8, 4)) }; + for (var offset = 16; offset + 4 <= boxSize; offset += 4) + { + brands.Add(Ascii(head.Slice(offset, 4))); + } + + var major = brands[0]; + if (AudioBrands.Contains(major)) + { + return null; // audio only: neither photo nor video + } + + if (AvifBrands.Contains(major)) + { + return new DetectedType(MediaKind.Photo, "image/avif", ".avif", "AVIF"); + } + + if (HeifBrands.Contains(major)) + { + return major is "mif1" or "msf1" or "mif2" && !brands.Exists(b => b is "heic" or "heix" or "hevc" or "hevx") + ? new DetectedType(MediaKind.Photo, "image/heif", ".heif", "HEIF") + : new DetectedType(MediaKind.Photo, "image/heic", ".heic", "HEIC"); + } + + if (major == "crx ") + { + return new DetectedType(MediaKind.Photo, "image/x-canon-cr3", ".cr3", "CR3"); + } + + if (major == "qt ") + { + return new DetectedType(MediaKind.Video, "video/quicktime", ".mov", "QuickTime"); + } + + if (ThreeGpBrands.Contains(major)) + { + return new DetectedType(MediaKind.Video, "video/3gpp", ".3gp", "3GP"); + } + + if (major.StartsWith("3g2", StringComparison.Ordinal)) + { + return new DetectedType(MediaKind.Video, "video/3gpp2", ".3g2", "3G2"); + } + + if (Mp4Brands.Contains(major)) + { + return new DetectedType(MediaKind.Video, "video/mp4", ".mp4", "MP4"); + } + + // Unknown major brand: decide from the compatible ones. + if (brands.Exists(AvifBrands.Contains)) + { + return new DetectedType(MediaKind.Photo, "image/avif", ".avif", "AVIF"); + } + + if (brands.Exists(HeifBrands.Contains)) + { + return new DetectedType(MediaKind.Photo, "image/heif", ".heif", "HEIF"); + } + + if (brands.Exists(b => b == "qt ")) + { + return new DetectedType(MediaKind.Video, "video/quicktime", ".mov", "QuickTime"); + } + + if (brands.Exists(Mp4Brands.Contains)) + { + return new DetectedType(MediaKind.Video, "video/mp4", ".mp4", "MP4"); + } + + return null; + } + + private static string Ascii(ReadOnlySpan bytes) => Encoding.Latin1.GetString(bytes); +} diff --git a/src/Febe.Core/Import/Mp4Reader.cs b/src/Febe.Core/Import/Mp4Reader.cs new file mode 100644 index 0000000..9a42453 --- /dev/null +++ b/src/Febe.Core/Import/Mp4Reader.cs @@ -0,0 +1,222 @@ +using System.Buffers.Binary; + +namespace Febe.Core.Import; + +/// What the moov box of an MP4 or QuickTime file says. +/// Creation time of the movie header (mvhd), when plausible. +/// Duration from mvhd. +/// Display width of the first video track (rotation applied). +/// Display height of the first video track (rotation applied). +public sealed record Mp4Info(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height); + +/// +/// Reads creation time, duration and size of MP4, MOV and 3GP files by walking their boxes (spec §9.2: «data di creazione +/// dei video»), written by hand. Only box headers are read: the media data (mdat) is skipped with a seek, so the +/// cost does not depend on the size of the file. The creation time is seconds since 1904-01-01 UTC; zero and +/// implausible values (before 1995 or in the future) are ignored, since many encoders leave it empty. +/// +public static class Mp4Reader +{ + private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset Earliest = new(1995, 1, 1, 0, 0, 0, TimeSpan.Zero); + + /// The largest moov box read into memory. + private const long MaxMoovBytes = 64L * 1024 * 1024; + + private const int MaxTopLevelBoxes = 10_000; + + /// Reads a file (read-only). Null when no moov box is found. + /// The file. + /// Current time: creation times after it (by more than a day) are ignored. + public static Mp4Info? ReadFile(string path, DateTimeOffset now) + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess); + return Read(stream, now); + } + + /// Reads a seekable stream from its start. Null when no moov box is found. + public static Mp4Info? Read(Stream stream, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(stream); + if (!stream.CanSeek) + { + throw new ArgumentException("Serve un flusso con posizionamento.", nameof(stream)); + } + + Span header = stackalloc byte[16]; + long position = 0; + var length = stream.Length; + for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++) + { + stream.Position = position; + if (stream.ReadAtLeast(header[..8], 8, throwOnEndOfStream: false) < 8) + { + return null; + } + + long size = BinaryPrimitives.ReadUInt32BigEndian(header); + var type = header.Slice(4, 4); + var headerSize = 8; + if (size == 1) + { + if (stream.ReadAtLeast(header.Slice(8, 8), 8, throwOnEndOfStream: false) < 8) + { + return null; + } + + size = (long)BinaryPrimitives.ReadUInt64BigEndian(header.Slice(8, 8)); + headerSize = 16; + } + else if (size == 0) + { + size = length - position; // to the end of the file + } + + if (size < headerSize || position + size > length + 8) + { + return null; // damaged + } + + if (type.SequenceEqual("moov"u8)) + { + var bodyLength = Math.Min(size - headerSize, length - position - headerSize); + if (bodyLength <= 0 || bodyLength > MaxMoovBytes) + { + return null; + } + + var body = new byte[bodyLength]; + stream.Position = position + headerSize; + stream.ReadExactly(body); + return ParseMoov(body, now); + } + + position += size; + } + + return null; + } + + /// Parses the content of a moov box. + internal static Mp4Info? ParseMoov(ReadOnlySpan moov, DateTimeOffset now) + { + DateTimeOffset? created = null; + TimeSpan? duration = null; + int? width = null, height = null; + try + { + foreach (var (type, start, count) in Children(moov)) + { + var body = moov.Slice(start, count); + if (type == "mvhd") + { + (created, duration) = ParseMvhd(body, now); + } + else if (type == "trak" && width is null) + { + foreach (var (childType, childStart, childCount) in Children(body)) + { + if (childType == "tkhd" && ParseTkhd(body.Slice(childStart, childCount)) is { } size) + { + (width, height) = size; + } + } + } + } + } + catch (ArgumentOutOfRangeException) + { + // A damaged box: keep what was read. + } + + return new Mp4Info(created, duration, width, height); + } + + private static (DateTimeOffset? Created, TimeSpan? Duration) ParseMvhd(ReadOnlySpan body, DateTimeOffset now) + { + var version = body[0]; + ulong creation; + uint timescale; + ulong duration; + if (version == 1) + { + creation = BinaryPrimitives.ReadUInt64BigEndian(body.Slice(4, 8)); + timescale = BinaryPrimitives.ReadUInt32BigEndian(body.Slice(20, 4)); + duration = BinaryPrimitives.ReadUInt64BigEndian(body.Slice(24, 8)); + } + else + { + creation = BinaryPrimitives.ReadUInt32BigEndian(body.Slice(4, 4)); + timescale = BinaryPrimitives.ReadUInt32BigEndian(body.Slice(12, 4)); + duration = BinaryPrimitives.ReadUInt32BigEndian(body.Slice(16, 4)); + } + + DateTimeOffset? created = null; + if (creation > 0 && creation < (ulong)TimeSpan.FromDays(400 * 365).TotalSeconds) + { + var instant = Epoch1904.AddSeconds(creation); + if (instant >= Earliest && instant <= now.AddDays(1)) + { + created = instant; + } + } + + TimeSpan? length = timescale > 0 && duration > 0 && duration != uint.MaxValue && duration != ulong.MaxValue + ? TimeSpan.FromSeconds((double)duration / timescale) + : null; + return (created, length); + } + + private static (int Width, int Height)? ParseTkhd(ReadOnlySpan body) + { + // version/flags (4), times and ids (20 or 32), reserved (8), layer, group, volume, reserved (8), matrix (36), width, height. + var offset = body[0] == 1 ? 4 + 32 : 4 + 20; + offset += 8 + 8; + var matrix = body.Slice(offset, 36); + var a = BinaryPrimitives.ReadInt32BigEndian(matrix[..4]); + var b = BinaryPrimitives.ReadInt32BigEndian(matrix.Slice(4, 4)); + offset += 36; + var width = (int)(BinaryPrimitives.ReadUInt32BigEndian(body.Slice(offset, 4)) >> 16); + var height = (int)(BinaryPrimitives.ReadUInt32BigEndian(body.Slice(offset + 4, 4)) >> 16); + if (width <= 0 || height <= 0) + { + return null; // an audio track + } + + // A rotation of 90 or 270 degrees: the matrix is [0 ±1; ∓1 0] in 16.16 fixed point. + var rotated = a == 0 && Math.Abs(b) == 0x10000; + return rotated ? (height, width) : (width, height); + } + + /// Child boxes of a box body: type, start and length of each body. + private static List<(string Type, int Start, int Length)> Children(ReadOnlySpan data) + { + var list = new List<(string, int, int)>(); + var offset = 0; + while (offset + 8 <= data.Length) + { + long size = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset, 4)); + var type = System.Text.Encoding.Latin1.GetString(data.Slice(offset + 4, 4)); + var headerSize = 8; + if (size == 1) + { + size = (long)BinaryPrimitives.ReadUInt64BigEndian(data.Slice(offset + 8, 8)); + headerSize = 16; + } + else if (size == 0) + { + size = data.Length - offset; + } + + if (size < headerSize || offset + size > data.Length) + { + break; + } + + list.Add((type, offset + headerSize, (int)size - headerSize)); + offset += (int)size; + } + + return list; + } +} diff --git a/src/Febe.Core/Import/Recognition.cs b/src/Febe.Core/Import/Recognition.cs new file mode 100644 index 0000000..4448d32 --- /dev/null +++ b/src/Febe.Core/Import/Recognition.cs @@ -0,0 +1,602 @@ +using System.Text; +using System.Text.RegularExpressions; +using Febe.Core.Domain; +using Febe.Core.Library; + +namespace Febe.Core.Import; + +/// +/// How a source is divided into folders that each go to one account (mockup 09, «Cartelle e account»). +/// +/// When the chosen folder holds only structural subfolders (post, storie, evidenza, taggati, years, ...) or only files, +/// the chosen folder itself is the unit: it is probably one account (e.g. /importa/marta.demo). Otherwise each +/// first-level subfolder is a unit (e.g. a Febe library or a 4K Stogram output folder with one folder per account), +/// and loose files at the top form the unit «» without a probable account. +/// +/// +public sealed partial class SourceLayout +{ + private static readonly HashSet StructuralNames = new(StringComparer.Ordinal) + { + "post", "posts", "reel", "reels", "feed", "storie", "storia", "stories", "story", "evidenza", "in evidenza", + "storie in evidenza", "highlights", "highlight", "taggati", "taggato", "tagged", "tag", "profilo", "profile", + "importati", + }; + + private SourceLayout(string root, bool rootIsAccount, IReadOnlyList firstLevelFolders) + { + Root = root; + RootName = Path.GetFileName(Path.TrimEndingDirectorySeparator(root)) is { Length: > 0 } name ? name : root; + RootIsAccount = rootIsAccount; + FirstLevelFolders = firstLevelFolders; + } + + /// Full path of the source folder. + public string Root { get; } + + /// Name of the source folder. + public string RootName { get; } + + /// The source folder itself is one unit (one account). + public bool RootIsAccount { get; } + + /// First-level subfolders, by name. + public IReadOnlyList FirstLevelFolders { get; } + + /// Looks at the first level of a source (read-only). + public static SourceLayout Inspect(string root) + { + ArgumentException.ThrowIfNullOrWhiteSpace(root); + var full = Path.GetFullPath(root); + var folders = Directory.EnumerateDirectories(full, "*", ImportSources.Enumeration(recursive: false)) + .Select(Path.GetFileName) + .OfType() + .Order(StringComparer.Ordinal) + .ToList(); + return new SourceLayout(full, folders.TrueForAll(IsStructural), folders); + } + + /// A layout without looking at the disk (tests, demo data). + public static SourceLayout Create(string root, bool rootIsAccount, IReadOnlyList? firstLevelFolders = null) => + new(Path.GetFullPath(root), rootIsAccount, firstLevelFolders ?? []); + + /// Folders of the source that are units, relative ('' for the source folder itself). + public IReadOnlyList UnitFolders => RootIsAccount ? [string.Empty] : [string.Empty, .. FirstLevelFolders]; + + /// The unit folder of a file and its path inside that folder ('/' separated). + public (string Folder, string PathInFolder) Split(string relativePath) + { + ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); + var stored = LibraryLayout.ToStored(relativePath); + var slash = stored.IndexOf('/', StringComparison.Ordinal); + return RootIsAccount || slash < 0 ? (string.Empty, stored) : (stored[..slash], stored[(slash + 1)..]); + } + + /// Full path of a unit folder. + public string FolderPath(string folder) => folder.Length == 0 ? Root : LibraryLayout.FullPath(Root, folder); + + /// Name shown for a unit folder: its own name, or the source name for the source itself. + public string DisplayName(string folder) => folder.Length == 0 ? RootName : folder; + + /// The name of the account folder a unit stands for, or null for loose files at the top of a multi-account source. + public string? AccountFolderName(string folder) => folder.Length > 0 ? folder : RootIsAccount ? RootName : null; + + /// True for folder names that describe the content (kind, year, month), not an account. + public static bool IsStructural(string name) + { + var normalized = Normalize(name); + return StructuralNames.Contains(normalized) || YearOrMonth().IsMatch(normalized); + } + + /// + /// The kind of content suggested by the folders above a file (spec §9.2: «tipo probabile dalle sottocartelle»), and + /// the highlight collection title (the folder below «evidenza» or «highlights»). + /// + public static (EntryKind? Kind, string? HighlightTitle) KindFromFolders(IReadOnlyList directories) + { + ArgumentNullException.ThrowIfNull(directories); + for (var i = 0; i < directories.Count; i++) + { + switch (Normalize(directories[i])) + { + case "evidenza" or "in evidenza" or "storie in evidenza" or "highlights" or "highlight": + var title = i + 1 < directories.Count && !YearOrMonth().IsMatch(directories[i + 1]) ? directories[i + 1] : null; + return (EntryKind.Highlight, title); + case "storie" or "storia" or "stories" or "story": + return (EntryKind.Story, null); + case "taggati" or "taggato" or "tagged" or "tag": + return (EntryKind.Tagged, null); + case "post" or "posts" or "reel" or "reels" or "feed": + return (EntryKind.Post, null); + case "profilo" or "profile": + return (EntryKind.ProfilePicture, null); + default: + break; + } + } + + return (null, null); + } + + /// + /// An Instagram user name from a folder name (lowercase), or null when the name cannot be one: letters, digits, + /// dots and underscores, at most 30, not only digits, no leading, trailing or double dot, not a structural name. + /// + public static string? UsernameFrom(string? folderName) + { + if (string.IsNullOrWhiteSpace(folderName)) + { + return null; + } + + var candidate = folderName.Trim().TrimStart('@').ToLowerInvariant(); + return Username().IsMatch(candidate) && !candidate.All(c => char.IsAsciiDigit(c) || c == '.') && !IsStructural(candidate) + ? candidate + : null; + } + + /// Lowercase, without accents, single spaces (underscores and dashes count as spaces). + internal static string Normalize(string name) + { + var decomposed = name.Trim().ToLowerInvariant().Normalize(NormalizationForm.FormD); + var builder = new StringBuilder(decomposed.Length); + var space = false; + foreach (var ch in decomposed) + { + if (System.Globalization.CharUnicodeInfo.GetUnicodeCategory(ch) == System.Globalization.UnicodeCategory.NonSpacingMark) + { + continue; + } + + if (ch is ' ' or '_' or '-') + { + space = builder.Length > 0; + continue; + } + + if (space) + { + builder.Append(' '); + space = false; + } + + builder.Append(ch); + } + + return builder.ToString(); + } + + [GeneratedRegex(@"^\d{4}$|^\d{2}$", RegexOptions.CultureInvariant)] + private static partial Regex YearOrMonth(); + + [GeneratedRegex(@"^(?!\.)(?!.*\.\.)[a-z0-9._]{1,30}(?A file of a source as the recognizers see it. +public sealed class ImportFileContext +{ + /// The source. + /// Path relative to the source, '/' separated. + public ImportFileContext(SourceLayout layout, string relativePath) + { + ArgumentNullException.ThrowIfNull(layout); + Layout = layout; + RelativePath = LibraryLayout.ToStored(relativePath); + (Folder, PathInFolder) = layout.Split(RelativePath); + FileName = RelativePath[(RelativePath.LastIndexOf('/') + 1)..]; + var parts = PathInFolder.Split('/'); + Directories = parts.Length <= 1 ? [] : parts[..^1]; + } + + public SourceLayout Layout { get; } + + /// Path relative to the source, '/' separated. + public string RelativePath { get; } + + /// The unit folder ('' for the source itself). + public string Folder { get; } + + /// Path inside the unit folder, '/' separated. + public string PathInFolder { get; } + + public string FileName { get; } + + /// Folders between the unit folder and the file. + public IReadOnlyList Directories { get; } + + /// The name without extension and without the « (2)» a copy may carry. + public string Stem => StripCopySuffix(Path.GetFileNameWithoutExtension(FileName)); + + public string Extension => Path.GetExtension(FileName); + + private static string StripCopySuffix(string stem) + { + var open = stem.LastIndexOf(" (", StringComparison.Ordinal); + return open > 0 && stem.EndsWith(')') && stem.Length - open > 3 && stem[(open + 2)..^1].All(char.IsAsciiDigit) ? stem[..open] : stem; + } +} + +/// +/// What a recognizer understood of one file. Fields left null are filled by the next recognizer (the generic one +/// always runs last). The caption is never printed by . +/// +public sealed record FileHints +{ + /// Name of the recognizer that gave the identity (). + public string? Recognizer { get; init; } + + /// The identity comes from an unverified hypothesis (4K Stogram, spec §9.6). + public bool Hypothesis { get; init; } + + public DateTimeOffset? Date { get; init; } + + /// or . + public ImportDateSource? DateSource { get; init; } + + /// Only the day was known. + public bool DateIsDayOnly { get; init; } + + /// Instagram identifier of the entry. + public string? InstagramId { get; init; } + + /// Instagram identifier of this item of a series. + public string? MediaInstagramId { get; init; } + + /// Post code (short code). + public string? Code { get; init; } + + /// Position in the series ({n}). + public int? Position { get; init; } + + public string? AccountUsername { get; init; } + + public string? AccountInstagramId { get; init; } + + public EntryKind? Kind { get; init; } + + public string? HighlightTitle { get; init; } + + /// Caption (Febe journal only). Never logged. + public string? Caption { get; init; } + + public string? AuthorUsername { get; init; } + + public string? AuthorInstagramId { get; init; } + + /// These hints, with the missing fields taken from . + public FileHints Merge(FileHints? fallback) + { + if (fallback is null) + { + return this; + } + + var useOwnDate = Date is not null; + return new FileHints + { + Recognizer = Recognizer ?? fallback.Recognizer, + Hypothesis = Recognizer is not null ? Hypothesis : fallback.Hypothesis, + Date = useOwnDate ? Date : fallback.Date, + DateSource = useOwnDate ? DateSource : fallback.DateSource, + DateIsDayOnly = useOwnDate ? DateIsDayOnly : fallback.DateIsDayOnly, + InstagramId = InstagramId ?? fallback.InstagramId, + MediaInstagramId = MediaInstagramId ?? fallback.MediaInstagramId, + Code = Code ?? fallback.Code, + Position = Position ?? fallback.Position, + AccountUsername = AccountUsername ?? fallback.AccountUsername, + AccountInstagramId = AccountInstagramId ?? fallback.AccountInstagramId, + Kind = Kind ?? fallback.Kind, + HighlightTitle = HighlightTitle ?? fallback.HighlightTitle, + Caption = Caption ?? fallback.Caption, + AuthorUsername = AuthorUsername ?? fallback.AuthorUsername, + AuthorInstagramId = AuthorInstagramId ?? fallback.AuthorInstagramId, + }; + } + + // Keeps the caption out of ToString(): records are easy to log by mistake. + private bool PrintMembers(StringBuilder builder) + { + builder.Append($"Recognizer = {Recognizer}, Hypothesis = {Hypothesis}, Date = {Date:O}, DateSource = {DateSource}, "); + builder.Append($"InstagramId = {InstagramId}, Code = {Code}, Position = {Position}, AccountUsername = {AccountUsername}, Kind = {Kind}"); + return true; + } +} + +/// +/// Understands the files of one kind of source (spec §9.2, §9.6): Febe's own library, the generic one, 4K Stogram +/// (hypothesis). Recognizers only read: they never write into the source. +/// +public interface IImportRecognizer +{ + /// Stable name, e.g. «febe». + string Name { get; } + + /// Name for Alberto, in Italian. + string Label { get; } + + /// The recognizer rests on an unverified hypothesis. + bool IsHypothesis { get; } + + /// Reads what it needs from the source once (e.g. the _febe.jsonl files), read-only. + Task PrepareAsync(SourceLayout layout, CancellationToken ct); + + /// The hints for a file, or null when the file is not of this kind. + FileHints? Recognize(ImportFileContext file); +} + +/// The recognizers of an analysis, in order of trust; the generic one runs last and always answers. +public sealed class ImportRecognizers +{ + private readonly IReadOnlyList _items; + + public ImportRecognizers(IReadOnlyList items) + { + ArgumentNullException.ThrowIfNull(items); + _items = items; + } + + public IReadOnlyList Items => _items; + + /// Febe, then (only when asked) the 4K Stogram hypothesis, then the generic recognizer. + public static ImportRecognizers Create(TimeZoneInfo zone, Func now, bool stogramHypothesis) + { + var list = new List { new FebeRecognizer(zone) }; + if (stogramHypothesis) + { + list.Add(new StogramHypothesisRecognizer(zone)); + } + + list.Add(new GenericRecognizer(zone, now)); + return new ImportRecognizers(list); + } + + public async Task PrepareAsync(SourceLayout layout, CancellationToken ct) + { + foreach (var recognizer in _items) + { + await recognizer.PrepareAsync(layout, ct).ConfigureAwait(false); + } + } + + /// The hints of every recognizer that knows the file, the most trusted first. + public FileHints Recognize(ImportFileContext file) + { + ArgumentNullException.ThrowIfNull(file); + FileHints? merged = null; + foreach (var recognizer in _items) + { + if (recognizer.Recognize(file) is { } hints) + { + merged = merged is null ? hints : merged.Merge(hints); + } + } + + return merged ?? new FileHints(); + } +} + +/// +/// The generic recognizer: probable account from the folder name, probable kind from the subfolders, date from the +/// file name. No Instagram identifier: names of unknown tools are not guessed (rule 10). +/// +public sealed class GenericRecognizer(TimeZoneInfo zone, Func now) : IImportRecognizer +{ + public string Name => "generico"; + + public string Label => "Generico"; + + public bool IsHypothesis => false; + + public Task PrepareAsync(SourceLayout layout, CancellationToken ct) => Task.CompletedTask; + + public FileHints? Recognize(ImportFileContext file) + { + ArgumentNullException.ThrowIfNull(file); + var (kind, title) = SourceLayout.KindFromFolders(file.Directories); + var date = FileNameDates.Find(file.Stem, zone, now()); + return new FileHints + { + AccountUsername = SourceLayout.UsernameFrom(file.Layout.AccountFolderName(file.Folder)), + Kind = kind, + HighlightTitle = title, + Date = date?.Instant, + DateSource = date is null ? null : ImportDateSource.FileName, + DateIsDayOnly = date?.DayOnly ?? false, + }; + } +} + +/// +/// Febe's own library as a source (spec §4.7, §8.5): account folders with _febe.jsonl give identifiers, exact +/// publication times, captions, positions and collections; names made by the default scheme +/// ({data}_{ora}_{codice}_{n} under post, storie, evidenza/{raccolta}, taggati, +/// profilo) give date, code and position even without the journal. +/// +public sealed partial class FebeRecognizer(TimeZoneInfo zone) : IImportRecognizer +{ + private readonly Dictionary> _journals = new(StringComparer.Ordinal); + + public string Name => "febe"; + + public string Label => "Libreria di Febe"; + + public bool IsHypothesis => false; + + /// Unit folders whose journal was read. + public IReadOnlyCollection FoldersWithJournal => _journals.Keys; + + public async Task PrepareAsync(SourceLayout layout, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(layout); + _journals.Clear(); + foreach (var folder in layout.UnitFolders) + { + var path = layout.FolderPath(folder); + if (!File.Exists(AccountJournal.PathFor(path))) + { + continue; + } + + var content = await AccountJournal.ReadAsync(path, ct).ConfigureAwait(false); + var map = new Dictionary(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + foreach (var line in content.Lines) + { + foreach (var file in line.Files ?? []) + { + var key = LibraryLayout.ToStored(file.Path); + if (line.Op == JournalOps.Save) + { + map[key] = (line, file); + } + else + { + map.Remove(key); + } + } + } + + _journals[folder] = map; + } + } + + public FileHints? Recognize(ImportFileContext file) + { + ArgumentNullException.ThrowIfNull(file); + if (_journals.TryGetValue(file.Folder, out var map) && map.TryGetValue(file.PathInFolder, out var known)) + { + var (line, journalFile) = known; + return new FileHints + { + Recognizer = Name, + Date = line.Entry.PublishedAt, + DateSource = ImportDateSource.Journal, + InstagramId = Blank(line.Entry.Id), + MediaInstagramId = Blank(journalFile.Id), + Code = Blank(line.Entry.Code), + Position = journalFile.N, + AccountUsername = SourceLayout.UsernameFrom(line.Account.Username) ?? line.Account.Username.ToLowerInvariant(), + AccountInstagramId = Blank(line.Account.Id), + Kind = line.Kind, + HighlightTitle = line.Entry.Highlights is { Count: > 0 } highlights ? highlights[0].Title : null, + Caption = line.Entry.Caption, + AuthorUsername = line.Entry.Author, + AuthorInstagramId = line.Entry.AuthorId, + }; + } + + var match = DefaultName().Match(file.Stem); + if (!match.Success || match.Groups["code"].Value == "UTC") + { + return null; // «…_UTC_1» is Instaloader's naming, not Febe's: the generic recognizer reads it as UTC + } + + int Part(string name) => int.Parse(match.Groups[name].Value, System.Globalization.CultureInfo.InvariantCulture); + DateTime local; + try + { + local = new DateTime(Part("y"), Part("mo"), Part("d"), Part("h"), Part("mi"), Part("s"), DateTimeKind.Unspecified); + } + catch (ArgumentOutOfRangeException) + { + return null; + } + + var (kind, title) = FebeKind(file.Directories); + var code = match.Groups["code"].Value; + var isIdentity = kind != EntryKind.ProfilePicture && !string.Equals(code, "senza-codice", StringComparison.Ordinal); + var numeric = code.All(char.IsAsciiDigit); + return new FileHints + { + Recognizer = Name, + Date = LocalCalendar.FromLocal(local, zone), + DateSource = ImportDateSource.FileName, + InstagramId = isIdentity && numeric ? code : null, + Code = isIdentity && !numeric ? code : null, + Position = Part("n") is var n && n >= 1 ? n : (int?)null, + Kind = kind, + HighlightTitle = title, + }; + } + + /// Kind from Febe's own folder names right below the account folder. + private static (EntryKind? Kind, string? Title) FebeKind(IReadOnlyList directories) + { + if (directories.Count == 0) + { + return (null, null); + } + + var kind = EntryKindNames.FromFolder(directories[0]); + var title = kind == EntryKind.Highlight && directories.Count > 1 ? directories[1] : null; + return (kind, title); + } + + private static string? Blank(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + [GeneratedRegex(@"^(?\d{4})-(?\d{2})-(?\d{2})_(?\d{2})-(?\d{2})-(?\d{2})_(?[A-Za-z0-9_\-]+)_(?\d{1,3})$", RegexOptions.CultureInvariant)] + private static partial Regex DefaultName(); +} + +/// +/// Hypothesis, not verified (spec §9.6): 4K Stogram names its files «AAAA-MM-GG HH.MM.SS <id contenuto>_<id +/// utente>.jpg» in one folder per account, with subfolders for stories, highlights and tagged posts. This comes from a +/// memory, not from real data: the specification asks for about twenty real file names and the schema of +/// stogram.sqlite before writing the recognizer for real. Until then it is off unless asked for +/// (), it is tested only on synthetic names, and it never opens +/// stogram.sqlite. The time in the name is read as local time (also a hypothesis). +/// +public sealed partial class StogramHypothesisRecognizer(TimeZoneInfo zone) : IImportRecognizer +{ + /// Files that 4K Stogram keeps in its output folder (verified, spec §9.6). Their presence is only looked at. + public static IReadOnlyList DatabaseFiles { get; } = ["stogram.sqlite", "stogram.app.sqlite", "stogram.sqlite.backup"]; + + public string Name => "4k-stogram-ipotesi"; + + public string Label => "4K Stogram (ipotesi da verificare)"; + + public bool IsHypothesis => true; + + /// True when the folder holds one of the 4K Stogram database files (only their existence is checked). + public static bool LooksLikeStogramFolder(string folder) => + Directory.Exists(folder) && DatabaseFiles.Any(name => File.Exists(Path.Combine(folder, name))); + + public Task PrepareAsync(SourceLayout layout, CancellationToken ct) => Task.CompletedTask; + + public FileHints? Recognize(ImportFileContext file) + { + ArgumentNullException.ThrowIfNull(file); + var match = StogramName().Match(file.Stem); + if (!match.Success) + { + return null; + } + + int Part(string name) => int.Parse(match.Groups[name].Value, System.Globalization.CultureInfo.InvariantCulture); + DateTime local; + try + { + local = new DateTime(Part("y"), Part("mo"), Part("d"), Part("h"), Part("mi"), Part("s"), DateTimeKind.Unspecified); + } + catch (ArgumentOutOfRangeException) + { + return null; + } + + var (kind, title) = SourceLayout.KindFromFolders(file.Directories); + return new FileHints + { + Recognizer = Name, + Hypothesis = true, + Date = LocalCalendar.FromLocal(local, zone), + DateSource = ImportDateSource.FileName, + InstagramId = match.Groups["content"].Value, + AccountInstagramId = match.Groups["user"].Value, + Kind = kind, + HighlightTitle = title, + }; + } + + [GeneratedRegex(@"^(?\d{4})-(?\d{2})-(?\d{2}) (?\d{2})\.(?\d{2})\.(?\d{2}) (?\d{5,})_(?\d{3,})$", RegexOptions.CultureInvariant)] + private static partial Regex StogramName(); +} diff --git a/src/Febe.Core/Import/VideoMetadataProbe.cs b/src/Febe.Core/Import/VideoMetadataProbe.cs new file mode 100644 index 0000000..eef40f1 --- /dev/null +++ b/src/Febe.Core/Import/VideoMetadataProbe.cs @@ -0,0 +1,182 @@ +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; + +namespace Febe.Core.Import; + +/// Metadata of a video read by an external tool. +public sealed record VideoMetadata(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height); + +/// +/// Reads creation time, duration and size of videos the hand-written reader does not cover (WebM, Matroska, AVI, ...). +/// Optional: the analysis works without it (spec §9.2: «oppure si usa ffprobe dove è presente»). +/// +public interface IVideoMetadataProbe +{ + /// Metadata of a video file, read-only; null when the tool cannot read it. + Task ProbeAsync(string path, CancellationToken ct = default); +} + +/// +/// with ffprobe, when installed (in Docker it comes with ffmpeg, §11). The output is +/// parsed with ; error output is never logged (it may contain paths). +/// +public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe +{ + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(20); + + private FfprobeVideoMetadataProbe(string executable) => Executable = executable; + + /// Full path of ffprobe. + public string Executable { get; } + + /// Finds ffprobe on the PATH (or at ); null when it is not available. + public static FfprobeVideoMetadataProbe? TryCreate(string? explicitPath = null) + { + if (!string.IsNullOrWhiteSpace(explicitPath)) + { + return File.Exists(explicitPath) ? new FfprobeVideoMetadataProbe(Path.GetFullPath(explicitPath)) : null; + } + + var name = OperatingSystem.IsWindows() ? "ffprobe.exe" : "ffprobe"; + foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + try + { + var candidate = Path.Combine(folder.Trim('"'), name); + if (File.Exists(candidate)) + { + return new FfprobeVideoMetadataProbe(candidate); + } + } + catch (ArgumentException) + { + // A malformed PATH entry: skip it. + } + } + + return null; + } + + public async Task ProbeAsync(string path, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + var start = new ProcessStartInfo(Executable) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + foreach (var argument in new[] + { + "-hide_banner", "-v", "error", "-print_format", "json", + "-show_entries", "format=duration:format_tags=creation_time:stream=codec_type,width,height:stream_tags=rotate,creation_time", + "-i", path, + }) + { + start.ArgumentList.Add(argument); + } + + using var process = new Process { StartInfo = start }; + try + { + if (!process.Start()) + { + return null; + } + } + catch (System.ComponentModel.Win32Exception) + { + return null; + } + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(Timeout); + string output; + try + { + var read = process.StandardOutput.ReadToEndAsync(timeout.Token); + var drain = process.StandardError.ReadToEndAsync(timeout.Token); + await Task.WhenAll(read, drain).ConfigureAwait(false); + await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false); + output = read.Result; + } + catch (OperationCanceledException) + { + try + { + process.Kill(entireProcessTree: true); + } + catch (InvalidOperationException) + { + } + + ct.ThrowIfCancellationRequested(); + return null; + } + + return process.ExitCode == 0 ? Parse(output) : null; + } + + /// Parses the JSON printed by ffprobe. + internal static VideoMetadata? Parse(string json) + { + try + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + DateTimeOffset? created = null; + TimeSpan? duration = null; + int? width = null, height = null; + if (root.TryGetProperty("format", out var format)) + { + if (format.TryGetProperty("duration", out var d) && d.ValueKind == JsonValueKind.String + && double.TryParse(d.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var seconds) && seconds > 0) + { + duration = TimeSpan.FromSeconds(seconds); + } + + created = CreationTime(format); + } + + if (root.TryGetProperty("streams", out var streams) && streams.ValueKind == JsonValueKind.Array) + { + foreach (var stream in streams.EnumerateArray()) + { + if (stream.TryGetProperty("codec_type", out var type) && type.ValueKind == JsonValueKind.String && type.GetString() == "video" + && stream.TryGetProperty("width", out var w) && w.TryGetInt32(out var wv) && wv > 0 + && stream.TryGetProperty("height", out var h) && h.TryGetInt32(out var hv) && hv > 0) + { + var rotate = stream.TryGetProperty("tags", out var tags) && tags.TryGetProperty("rotate", out var r) + && int.TryParse(r.ValueKind == JsonValueKind.String ? r.GetString() : r.GetRawText(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var degrees) + ? Math.Abs(degrees) % 180 + : 0; + (width, height) = rotate == 90 ? (hv, wv) : (wv, hv); + created ??= CreationTime(stream); + break; + } + } + } + + return new VideoMetadata(created, duration, width, height); + } + catch (Exception ex) when (ex is JsonException or InvalidOperationException or FormatException) + { + return null; // an unexpected shape: as if ffprobe had nothing to say + } + } + + private static DateTimeOffset? CreationTime(JsonElement element) + { + if (element.TryGetProperty("tags", out var tags) && tags.ValueKind == JsonValueKind.Object + && tags.TryGetProperty("creation_time", out var value) && value.ValueKind == JsonValueKind.String + && DateTimeOffset.TryParse(value.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var instant) + && instant.Year >= 1995) + { + return instant.ToUniversalTime(); + } + + return null; + } +} diff --git a/src/Febe.Core/Library/LibraryIngest.cs b/src/Febe.Core/Library/LibraryIngest.cs index c7c433d..513cf82 100644 --- a/src/Febe.Core/Library/LibraryIngest.cs +++ b/src/Febe.Core/Library/LibraryIngest.cs @@ -17,6 +17,37 @@ public sealed record MediaContent /// Drop the file beyond this size («Salta i video oltre», spec §4.4). public long? MaxBytes { get; init; } + + /// + /// Path relative to the account folder ('/' separated) to use instead of the naming scheme: imported files without + /// a known date and code go to importati/ with their original name (spec §9.4). A taken name still becomes + /// «nome (2).ext»: nothing is overwritten. + /// + public string? FixedRelativePath { get; init; } + + /// + /// The SHA-256 the content must have (lowercase hex), e.g. the one measured by the analysis of an import. When the + /// bytes read differ, nothing is kept and is thrown. + /// + public string? ExpectedSha256 { get; init; } +} + +/// The content read differs from : nothing was kept. +public sealed class ContentChangedException : IOException +{ + public ContentChangedException() + { + } + + public ContentChangedException(string message) + : base(message) + { + } + + public ContentChangedException(string message, Exception innerException) + : base(message, innerException) + { + } } public enum MediaSaveOutcome @@ -92,7 +123,9 @@ public sealed class LibraryIngest( var folder = layout.AccountFolder(account); var scheme = naming.For(entry.Kind); var zone = clock.LocalZone; - var provisional = layout.RelativePathFor(folder, scheme, NamingValues.For(account.Username, entry, media.Position, content.Extension, highlightTitle), zone); + var provisional = content.FixedRelativePath is { } fixedPath + ? LibraryLayout.ToStored(fixedPath) + : layout.RelativePathFor(folder, scheme, NamingValues.For(account.Username, entry, media.Position, content.Extension, highlightTitle), zone); var directory = provisional.Contains('/', StringComparison.Ordinal) ? provisional[..provisional.LastIndexOf('/')] : string.Empty; MediaLocation? identical = null; @@ -102,10 +135,20 @@ public sealed class LibraryIngest( directory, async (digest, token) => { + if (content.ExpectedSha256 is { } expected && !string.Equals(expected, digest.Sha256, StringComparison.OrdinalIgnoreCase)) + { + throw new ContentChangedException("Il contenuto letto è diverso da quello atteso: il file non viene salvato."); + } + var same = await storage.Media.FindBySha256Async(digest.Sha256, token).ConfigureAwait(false); identical = same.FirstOrDefault(s => s.Entry.AccountId == account.Id && s.Media.Id != media.Id && EntryStateRules.IsPresent(s.Media.State)); - return identical is not null - ? null + if (identical is not null) + { + return null; + } + + return content.FixedRelativePath is not null + ? provisional : layout.RelativePathFor(folder, scheme, NamingValues.For(account.Username, entry, media.Position, content.Extension, highlightTitle, digest.Sha256), zone); }, new SafeWriteOptions diff --git a/src/Febe.Core/Storage/IImportStore.cs b/src/Febe.Core/Storage/IImportStore.cs index a5b8556..85d243d 100644 --- a/src/Febe.Core/Storage/IImportStore.cs +++ b/src/Febe.Core/Storage/IImportStore.cs @@ -42,8 +42,72 @@ public interface IImportStore /// Associates every file of a source folder with an account (null: not associated). Task SetFolderTargetAsync(long runId, string folder, long? accountId, CancellationToken ct = default); + + /// Source folders with their counts by outcome and their association (review table, mockup 09). + Task> ListFolderCountsAsync(long runId, CancellationToken ct = default); + + /// + /// Probable-duplicate pairs of an import (the candidate side is always a file of the import), in creation order. + /// + Task> ListPairsAsync(long runId, bool pendingOnly, long afterId = 0, int limit = 500, CancellationToken ct = default); + + Task CountPairsAsync(long runId, bool pendingOnly, CancellationToken ct = default); + + /// + /// Rows for the final report and the CSV export, by key: each file with the account and path of the library file it + /// matched and the user name of its destination account. + /// + Task> ListReportRowsAsync(long runId, long afterId = 0, int limit = 1000, CancellationToken ct = default); + + /// Removes the pairs of an import still waiting for a decision (the import was cancelled). Returns how many. + Task RemovePendingPairsAsync(long runId, CancellationToken ct = default); + + /// Removes an import with its files and pairs. Only records: no file on disk is touched. + Task DeleteRunAsync(long runId, CancellationToken ct = default); + + /// + /// Instagram identifiers and post codes of the whole library (entries in any state, files with their own + /// identifier), loaded once per analysis for the «same identifier, different file» comparison (spec §9.3). + /// + Task LoadLibraryIdentifiersAsync(CancellationToken ct = default); + + /// The entry of (account, kind) with this post code, in any state: imported posts known only by their code. + Task FindEntryByCodeAsync(long accountId, EntryKind kind, string code, CancellationToken ct = default); } +/// A source folder of an import with its counts by outcome. +/// Folder relative to the source ('/' separated, empty for the root). +/// Files of the folder. +/// Their total size. +/// Account guessed from the folder name. +/// Associated account, when chosen. +/// Files per outcome (every outcome present, zero included). +/// Files whose Instagram identifier or code is known. +public sealed record ImportFolderCounts( + string Folder, + int Files, + long Bytes, + string? ProbableAccount, + long? TargetAccountId, + IReadOnlyDictionary ByOutcome, + int Recognized); + +/// A file of an import for the report, with what it matched and where it went. +/// The file. +/// Account of the library file it matched («Già in libreria», «Doppione probabile»). +/// Path of that library file, relative to its account folder. +/// User name of the destination account. +public sealed record ImportReportRow(ImportFile File, string? MatchedUsername, string? MatchedPath, string? TargetUsername); + +/// Identity of an entry of the library: Instagram identifier and post code. +public sealed record EntryIdentity(long EntryId, long AccountId, EntryKind Kind, EntryState State, string? InstagramId, string? Code); + +/// A file of the library with its own Instagram identifier (an item of a series). +public sealed record MediaIdentity(long MediaId, long EntryId, string InstagramId); + +/// Identifiers of the whole library. +public sealed record LibraryIdentifiers(IReadOnlyList Entries, IReadOnlyList Media); + /// Filters for the files of an import. public sealed record ImportFileQuery { diff --git a/src/Febe.Data/Stores/ImportStore.cs b/src/Febe.Data/Stores/ImportStore.cs index 2d673af..b68ce2f 100644 --- a/src/Febe.Data/Stores/ImportStore.cs +++ b/src/Febe.Data/Stores/ImportStore.cs @@ -1,6 +1,7 @@ using Febe.Core.Domain; using Febe.Core.Storage; using Microsoft.Data.Sqlite; +using static Febe.Data.Stores.EntryMapping; namespace Febe.Data.Stores; @@ -13,6 +14,8 @@ internal sealed class ImportStore(FebeDatabase db) : IImportStore + "taken_at, date_source, instagram_id, code, probable_account, probable_kind, highlight_title, outcome, matched_media_id, " + "target_account_id, decision, state, entry_id, destination_path, last_error"; + private const int FileColumnCount = 28; + private static ImportRun ReadRun(SqliteDataReader r) => new() { Id = r.GetInt64(0), @@ -308,4 +311,186 @@ internal sealed class ImportStore(FebeDatabase db) : IImportStore .With("@a", Sql.Int(accountId)).With("@r", runId).With("@f", folder).ExecuteNonQuery(), ct); } + + public Task> ListFolderCountsAsync(long runId, CancellationToken ct = default) => + db.ReadAsync>( + c => + { + var folders = new Dictionary(StringComparer.Ordinal); + using (var r = c.Command(""" + SELECT folder, outcome, COUNT(*), COALESCE(SUM(bytes), 0), MAX(probable_account), MAX(target_account_id), + SUM(CASE WHEN instagram_id IS NOT NULL OR code IS NOT NULL THEN 1 ELSE 0 END) + FROM import_file WHERE run_id = @r GROUP BY folder, outcome + """).With("@r", runId).ExecuteReader()) + { + while (r.Read()) + { + var folder = r.GetString(0); + if (!folders.TryGetValue(folder, out var acc)) + { + acc = new FolderAccumulator(); + folders[folder] = acc; + } + + var count = r.GetInt32(2); + acc.ByOutcome[r.GetEnum(1)] += count; + acc.Files += count; + acc.Bytes += r.GetInt64(3); + acc.ProbableAccount ??= r.GetTextOrNull(4); + acc.TargetAccountId ??= r.GetInt64OrNull(5); + acc.Recognized += r.GetInt32(6); + } + } + + return folders + .OrderBy(f => f.Key, StringComparer.Ordinal) + .Select(f => new ImportFolderCounts(f.Key, f.Value.Files, f.Value.Bytes, f.Value.ProbableAccount, f.Value.TargetAccountId, f.Value.ByOutcome, f.Value.Recognized)) + .ToList(); + }, + ct); + + public Task> ListPairsAsync(long runId, bool pendingOnly, long afterId = 0, int limit = 500, CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var r = c.Command(""" + SELECT p.id, p.origin, p.reason, p.existing_media_id, p.existing_import_file_id, p.candidate_media_id, + p.candidate_import_file_id, p.distance, p.decision, p.created_at, p.decided_at + FROM duplicate_pair p JOIN import_file f ON f.id = p.candidate_import_file_id + WHERE f.run_id = @r AND p.id > @after AND (@pending = 0 OR p.decision = 'Pending') + ORDER BY p.id LIMIT @limit + """) + .With("@r", runId).With("@after", afterId).With("@pending", Sql.Bool(pendingOnly)) + .With("@limit", (long)Math.Clamp(limit, 1, 10_000)).ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(new DuplicatePair + { + Id = r.GetInt64(0), + Origin = r.GetEnum(1), + Reason = r.GetEnum(2), + ExistingMediaId = r.GetInt64OrNull(3), + ExistingImportFileId = r.GetInt64OrNull(4), + CandidateMediaId = r.GetInt64OrNull(5), + CandidateImportFileId = r.GetInt64OrNull(6), + Distance = r.GetInt32OrNull(7), + Decision = r.GetEnum(8), + CreatedAt = r.GetTime(9), + DecidedAt = r.GetTimeOrNull(10), + }); + } + + return list; + }, + ct); + + public Task CountPairsAsync(long runId, bool pendingOnly, CancellationToken ct = default) => + db.ReadAsync( + c => (int)c.Command(""" + SELECT COUNT(*) FROM duplicate_pair p JOIN import_file f ON f.id = p.candidate_import_file_id + WHERE f.run_id = @r AND (@pending = 0 OR p.decision = 'Pending') + """).With("@r", runId).With("@pending", Sql.Bool(pendingOnly)).ScalarInt64(), + ct); + + public Task> ListReportRowsAsync(long runId, long afterId = 0, int limit = 1000, CancellationToken ct = default) => + db.ReadAsync>( + c => + { + var columns = string.Join(", ", FileColumns.Split(", ").Select(column => "f." + column)); + using var r = c.Command($""" + SELECT {columns}, ma.username, mm.relative_path, ta.username + FROM import_file f + LEFT JOIN media mm ON mm.id = f.matched_media_id + LEFT JOIN entry me ON me.id = mm.entry_id + LEFT JOIN account ma ON ma.id = me.account_id + LEFT JOIN account ta ON ta.id = f.target_account_id + WHERE f.run_id = @r AND f.id > @after + ORDER BY f.id LIMIT @limit + """) + .With("@r", runId).With("@after", afterId).With("@limit", (long)Math.Clamp(limit, 1, 10_000)).ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(new ImportReportRow(ReadFile(r), r.GetTextOrNull(FileColumnCount), r.GetTextOrNull(FileColumnCount + 1), r.GetTextOrNull(FileColumnCount + 2))); + } + + return list; + }, + ct); + + public Task RemovePendingPairsAsync(long runId, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command(""" + DELETE FROM duplicate_pair WHERE decision = 'Pending' + AND candidate_import_file_id IN (SELECT id FROM import_file WHERE run_id = @r) + """).With("@r", runId).ExecuteNonQuery(), + ct); + + public Task DeleteRunAsync(long runId, CancellationToken ct = default) => + db.WriteAsync( + w => + { + // Pairs go by cascade with their import files; files on disk are never touched here. + w.Command("DELETE FROM import_run WHERE id = @r").With("@r", runId).ExecuteNonQuery(); + }, + ct); + + public Task LoadLibraryIdentifiersAsync(CancellationToken ct = default) => + db.ReadAsync( + c => + { + var entries = new List(); + using (var r = c.Command(""" + SELECT id, account_id, kind, state, instagram_id, code FROM entry + WHERE instagram_id IS NOT NULL OR code IS NOT NULL + """).ExecuteReader()) + { + while (r.Read()) + { + entries.Add(new EntryIdentity(r.GetInt64(0), r.GetInt64(1), r.GetEnum(2), r.GetEnum(3), r.GetTextOrNull(4), r.GetTextOrNull(5))); + } + } + + var media = new List(); + using (var r = c.Command("SELECT id, entry_id, instagram_id FROM media WHERE instagram_id IS NOT NULL").ExecuteReader()) + { + while (r.Read()) + { + media.Add(new MediaIdentity(r.GetInt64(0), r.GetInt64(1), r.GetString(2))); + } + } + + return new LibraryIdentifiers(entries, media); + }, + ct); + + public Task FindEntryByCodeAsync(long accountId, EntryKind kind, string code, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(code); + return db.ReadAsync( + c => + { + using var r = c.Command($""" + SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a AND e.kind = @k AND e.code = @c ORDER BY e.id LIMIT 1 + """).With("@a", accountId).With("@k", Sql.Enum(kind)).With("@c", code.Trim()).ExecuteReader(); + return r.Read() ? ReadEntry(r) : null; + }, + ct); + } + + private sealed class FolderAccumulator + { + public Dictionary ByOutcome { get; } = Enum.GetValues().ToDictionary(o => o, _ => 0); + + public int Files { get; set; } + + public long Bytes { get; set; } + + public string? ProbableAccount { get; set; } + + public long? TargetAccountId { get; set; } + + public int Recognized { get; set; } + } } diff --git a/tests/Febe.Tests/Import/ImportAnalysisTests.cs b/tests/Febe.Tests/Import/ImportAnalysisTests.cs new file mode 100644 index 0000000..cd16f2d --- /dev/null +++ b/tests/Febe.Tests/Import/ImportAnalysisTests.cs @@ -0,0 +1,279 @@ +using System.Security.Cryptography; +using Febe.Core.Domain; +using Febe.Core.Import; +using Febe.Core.Library; +using Febe.Tests.Import.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Import; + +[TestClass] +public sealed class ImportAnalysisTests +{ + [TestMethod] + public async Task AGeneratedSourceTreeIsAnalysedWithoutTouchingIt() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var named = bed.Write("marta.demo/IMG_20210506_070809.jpg", ImportTestFiles.Photo(1)); + bed.Write("marta.demo/storie/foto-exif.jpg", ImportTestFiles.PhotoWithExifDate(2, new DateTime(2020, 2, 3, 10, 0, 0))); + bed.Write("marta.demo/storie/video.mp4", ImportTestFiles.Mp4(new DateTimeOffset(2022, 7, 1, 18, 30, 0, TimeSpan.Zero), 1080, 1920, 15_000, payloadSeed: 7)); + bed.Write("marta.demo/vecchia.jpg", ImportTestFiles.Photo(3), new DateTime(2019, 1, 2, 3, 4, 5, DateTimeKind.Utc)); + bed.Write("marta.demo/note.txt", "Appunti, non una foto."u8.ToArray()); + bed.Write("marta.demo/travestita.png", ImportTestFiles.Photo(4, 320, 240)); + bed.Write("Foto sparse/a.jpg", ImportTestFiles.Photo(5)); + bed.Write("marta.demo/Thumbs.db", [1, 2, 3]); + var realVideo = Path.Combine(bed.Source, "marta.demo", "storie", "ffmpeg.mp4"); + var withFfmpeg = ImportTestFiles.TryMakeMp4WithFfmpeg(realVideo, new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero)); + var before = bed.Fingerprint(); + + var run = await bed.AnalyzeAsync(); + + Assert.AreEqual(ImportRunState.Reviewing, run.State); + Assert.IsNotNull(run.AnalyzedAt); + CollectionAssert.AreEqual(before.ToList(), bed.Fingerprint().ToList(), "L'analisi è in sola lettura: nessun file della sorgente cambia."); + var files = (await bed.FilesAsync(run.Id)).Where(f => !f.RelativePath.EndsWith("ffmpeg.mp4", StringComparison.Ordinal)).ToList(); + Assert.HasCount(7, files, "Thumbs.db non è un contenuto e non si elenca."); + if (withFfmpeg) + { + var real = await bed.FileAsync(run.Id, "marta.demo/storie/ffmpeg.mp4"); + Assert.AreEqual("video/mp4", real.ContentType); + Assert.AreEqual(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero), real.TakenAt, "Data di creazione del video, dal suo mvhd."); + Assert.AreEqual(ImportDateSource.Metadata, real.DateSource); + Assert.AreEqual((64, 48), (real.Width, real.Height)); + } + + Assert.IsTrue(files.All(f => f.State == ImportFileState.Analyzed)); + + var byName = await bed.FileAsync(run.Id, "marta.demo/IMG_20210506_070809.jpg"); + Assert.AreEqual(ImportOutcome.New, byName.Outcome); + Assert.AreEqual(MediaKind.Photo, byName.MediaKind); + Assert.AreEqual("image/jpeg", byName.ContentType); + Assert.AreEqual((800, 600), (byName.Width, byName.Height)); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(named))), byName.Sha256); + Assert.AreEqual(new FileInfo(named).Length, byName.Bytes); + Assert.IsNotNull(byName.PerceptualHash); + Assert.AreEqual(ImportDateSource.FileName, byName.DateSource); + Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 5, 8, 9, TimeSpan.Zero), byName.TakenAt); + Assert.AreEqual("marta.demo", byName.Folder); + Assert.AreEqual("marta.demo", byName.ProbableAccount); + Assert.IsNull(byName.ProbableKind); + + var exif = await bed.FileAsync(run.Id, "marta.demo/storie/foto-exif.jpg"); + Assert.AreEqual(ImportDateSource.Metadata, exif.DateSource); + Assert.AreEqual(new DateTimeOffset(2020, 2, 3, 9, 0, 0, TimeSpan.Zero), exif.TakenAt); + Assert.AreEqual(EntryKind.Story, exif.ProbableKind); + + var video = await bed.FileAsync(run.Id, "marta.demo/storie/video.mp4"); + Assert.AreEqual(MediaKind.Video, video.MediaKind); + Assert.AreEqual(ImportDateSource.Metadata, video.DateSource); + Assert.AreEqual(new DateTimeOffset(2022, 7, 1, 18, 30, 0, TimeSpan.Zero), video.TakenAt); + Assert.AreEqual(TimeSpan.FromSeconds(15), video.Duration); + Assert.AreEqual((1080, 1920), (video.Width, video.Height)); + Assert.IsNull(video.PerceptualHash, "I video non hanno impronta visiva."); + + var old = await bed.FileAsync(run.Id, "marta.demo/vecchia.jpg"); + Assert.AreEqual(ImportDateSource.ModifiedTime, old.DateSource); + Assert.AreEqual(new DateTimeOffset(2019, 1, 2, 3, 4, 5, TimeSpan.Zero), old.TakenAt); + + Assert.AreEqual(ImportOutcome.Unrecognized, (await bed.FileAsync(run.Id, "marta.demo/note.txt")).Outcome); + Assert.AreEqual("image/jpeg", (await bed.FileAsync(run.Id, "marta.demo/travestita.png")).ContentType, "Il tipo viene dal contenuto."); + + var loose = await bed.FileAsync(run.Id, "Foto sparse/a.jpg"); + Assert.AreEqual("Foto sparse", loose.Folder); + Assert.IsNull(loose.ProbableAccount, "«Foto sparse» non può essere un nome utente."); + + var summary = await bed.Review.GetSummaryAsync(run.Id); + Assert.AreEqual(withFfmpeg ? 8 : 7, summary.Files); + Assert.AreEqual(withFfmpeg ? 7 : 6, summary.ByOutcome[ImportOutcome.New]); + Assert.AreEqual(1, summary.ByOutcome[ImportOutcome.Unrecognized]); + var marta = summary.Folders.Single(f => f.Folder == "marta.demo"); + Assert.AreEqual(FolderTargetKind.NewArchiveAccount, marta.Target.Kind, "Un nome valido senza account: nuovo account, solo archivio."); + Assert.AreEqual("marta.demo", marta.Target.Username); + Assert.AreEqual(FolderTargetKind.None, summary.Folders.Single(f => f.Folder == "Foto sparse").Target.Kind, "Nessun nome riconosciuto: nessuna scelta fatta."); + Assert.IsTrue(summary.CanMove); + StringAssert.StartsWith(summary.Headline, withFfmpeg ? "8 file, " : "7 file, "); + StringAssert.EndsWith(summary.Headline, "Nessun file è stato ancora copiato."); + } + + [TestMethod] + public async Task AnInterruptedAnalysisResumesWhereItStopped() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var twin = ImportTestFiles.Png(1000, 48, 36); + for (var i = 0; i < 100; i++) + { + bed.Write($"luca.demo/f{i:000}.png", i == 90 ? twin : ImportTestFiles.Png(1000 + i, 48, 36)); + } + + var info = bed.Environment.CreateSources().Inspect(bed.Source); + var run = await bed.Analyzer.CreateRunAsync(info); + using var stop = new CancellationTokenSource(); + var progress = new SyncProgress(p => + { + if (p.Phase == ImportPhase.Analyzing && p.FilesDone >= 64) + { + stop.Cancel(); + } + }); + + await Assert.ThrowsAsync(() => bed.Analyzer.AnalyzeAsync(run.Id, progress, stop.Token)); + var interrupted = await bed.Library.Db.Imports.GetRunAsync(run.Id); + Assert.AreEqual(ImportRunState.AnalysisInterrupted, interrupted!.State); + Assert.IsNull(interrupted.LastError, "Un'interruzione non è un errore."); + var halfway = await bed.FilesAsync(run.Id); + var analysed = halfway.Count(f => f.State == ImportFileState.Analyzed); + Assert.AreEqual(64, analysed, "Il primo gruppo di file è salvato con il suo esito."); + Assert.AreEqual(36, halfway.Count(f => f.State == ImportFileState.Pending)); + + var resumed = await bed.Analyzer.AnalyzeAsync(run.Id); + + Assert.AreEqual(ImportRunState.Reviewing, resumed.State); + var files = await bed.FilesAsync(run.Id); + Assert.HasCount(100, files, "Nessun file elencato due volte."); + Assert.IsTrue(files.All(f => f.State == ImportFileState.Analyzed && f.Outcome != ImportOutcome.Pending), "Un esito per ogni file."); + Assert.AreEqual(ImportOutcome.IdenticalInSource, files.Single(f => f.RelativePath == "luca.demo/f090.png").Outcome, "La copia identica è riconosciuta anche dopo la ripresa."); + Assert.AreEqual(99, files.Count(f => f.Outcome == ImportOutcome.New)); + } + + [TestMethod] + public async Task SameBytesAreAlreadyInTheLibraryAndTheReportSaysWhere() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var photo = ImportTestFiles.Photo(20); + var (luca, saved) = await bed.AccountWithPhotoAsync("luca.demo", "500", photo); + var (marta, savedMarta) = await bed.AccountWithPhotoAsync("marta.demo", "600", ImportTestFiles.Photo(21)); + bed.Write("marta.demo/copia.jpg", photo); + bed.Write("marta.demo/anche-questa.jpg", ImportTestFiles.Photo(21)); + + var run = await bed.AnalyzeAsync(); + + var copy = await bed.FileAsync(run.Id, "marta.demo/copia.jpg"); + Assert.AreEqual(ImportOutcome.AlreadyInLibrary, copy.Outcome); + Assert.AreEqual(saved.Media[0].Id, copy.MatchedMediaId); + var rows = await bed.Library.Db.Imports.ListReportRowsAsync(run.Id); + Assert.AreEqual("luca.demo", rows.Single(r => r.File.Id == copy.Id).MatchedUsername, "Il resoconto dice in quale account si trova."); + Assert.AreEqual(savedMarta.Media[0].Id, (await bed.FileAsync(run.Id, "marta.demo/anche-questa.jpg")).MatchedMediaId); + Assert.AreEqual(marta.Id, (await bed.Review.ListFoldersAsync(run.Id)).Single().Target.AccountId, "La cartella va all'account con lo stesso nome."); + Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import)); + _ = luca; + } + + [TestMethod] + public async Task TheDestinationAccountIsSearchedFirst() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var photo = ImportTestFiles.Photo(22); + await bed.AccountWithPhotoAsync("luca.demo", "700", photo); + var (_, inMarta) = await bed.AccountWithPhotoAsync("marta.demo", "701", photo); + bed.Write("marta.demo/x.jpg", photo); + + var run = await bed.AnalyzeAsync(); + + Assert.AreEqual(inMarta.Media[0].Id, (await bed.FileAsync(run.Id, "marta.demo/x.jpg")).MatchedMediaId); + } + + [TestMethod] + public async Task SameIdentifierWithADifferentFileIsAProbableDuplicate() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var account = await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var story = Make.Entry(account.Id, "3742118", new DateTimeOffset(2026, 10, 13, 7, 41, 7, TimeSpan.Zero), EntryKind.Story); + var saved = await bed.Library.SaveAsync(account, story, [new TestFile(Make.Photo(1), ImportTestFiles.Photo(30), ".jpg")]); + bed.Write("marta.demo/storie/2026/2026-10-13_09-41-07_3742118_1.jpg", ImportTestFiles.Photo(31)); + + var run = await bed.AnalyzeAsync(); + + var file = (await bed.FilesAsync(run.Id)).Single(); + Assert.AreEqual(ImportOutcome.ProbableDuplicate, file.Outcome); + Assert.AreEqual("3742118", file.InstagramId); + var pair = (await bed.Library.Db.Duplicates.ListPendingAsync(DuplicateOrigin.Import)).Single(); + Assert.AreEqual(DuplicateReason.SameInstagramId, pair.Reason); + Assert.AreEqual(saved.Media[0].Id, pair.ExistingMediaId); + Assert.AreEqual(file.Id, pair.CandidateImportFileId); + Assert.AreEqual(DuplicateDecision.Pending, pair.Decision, "Nessuna scelta è fatta in partenza."); + } + + [TestMethod] + public async Task AResizedCopyIsAProbableDuplicateAndACropIsNot() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var (_, saved) = await bed.AccountWithPhotoAsync("marta.demo", "800", ImportTestFiles.Photo(40, 800, 600, 92)); + bed.Write("marta.demo/piccola.jpg", ImportTestFiles.Resized(40, 800, 600, 400, 300, 55)); + bed.Write("marta.demo/ritaglio.jpg", ImportTestFiles.Cropped(40, 800, 600)); + bed.Write("marta.demo/altra.jpg", ImportTestFiles.Photo(41)); + + var run = await bed.AnalyzeAsync(); + + var resized = await bed.FileAsync(run.Id, "marta.demo/piccola.jpg"); + Assert.AreEqual(ImportOutcome.ProbableDuplicate, resized.Outcome); + var pair = (await bed.Review.ListDuplicatesAsync(run.Id)).Single(); + Assert.AreEqual(DuplicateReason.VisuallySimilar, pair.Pair.Reason); + Assert.AreEqual(saved.Media[0].Id, pair.Existing.MediaId); + Assert.IsTrue(pair.Existing.InLibrary); + Assert.AreEqual("marta.demo", pair.Existing.Username); + Assert.AreEqual(resized.Id, pair.Candidate.ImportFileId); + Assert.IsFalse(pair.CandidateIsLarger, "Quella in libreria ha più pixel."); + Assert.IsTrue(pair.Pair.Distance <= PerceptualHash.DuplicateThreshold); + + Assert.AreEqual(ImportOutcome.New, (await bed.FileAsync(run.Id, "marta.demo/ritaglio.jpg")).Outcome, "Un ritaglio non è un doppione."); + Assert.AreEqual(ImportOutcome.New, (await bed.FileAsync(run.Id, "marta.demo/altra.jpg")).Outcome); + } + + [TestMethod] + public async Task DuplicatesAreLookedForInsideTheSourceToo() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var photo = ImportTestFiles.Photo(50, 800, 600, 92); + bed.Write("marta.demo/a.jpg", photo); + bed.Write("marta.demo/backup/a.jpg", photo); + bed.Write("marta.demo/b-grande.jpg", ImportTestFiles.Photo(51, 800, 600, 92)); + bed.Write("marta.demo/c-piccola.jpg", ImportTestFiles.Resized(51, 800, 600, 400, 300, 55)); + bed.Write("marta.demo/d-video.mp4", ImportTestFiles.Mp4(null, payloadSeed: 3)); + bed.Write("marta.demo/e-video.mp4", ImportTestFiles.Mp4(null, payloadSeed: 4)); + + var run = await bed.AnalyzeAsync(); + + Assert.AreEqual(ImportOutcome.New, (await bed.FileAsync(run.Id, "marta.demo/a.jpg")).Outcome); + var copy = await bed.FileAsync(run.Id, "marta.demo/backup/a.jpg"); + Assert.AreEqual(ImportOutcome.IdenticalInSource, copy.Outcome); + StringAssert.Contains(copy.LastError, "marta.demo/a.jpg"); + var large = await bed.FileAsync(run.Id, "marta.demo/b-grande.jpg"); + var small = await bed.FileAsync(run.Id, "marta.demo/c-piccola.jpg"); + Assert.AreEqual(ImportOutcome.New, large.Outcome); + Assert.AreEqual(ImportOutcome.ProbableDuplicate, small.Outcome); + var pair = (await bed.Review.ListDuplicatesAsync(run.Id)).Single(); + Assert.IsTrue(pair.InsideSource); + Assert.AreEqual(large.Id, pair.Existing.ImportFileId); + Assert.AreEqual(small.Id, pair.Candidate.ImportFileId); + Assert.AreEqual(ImportOutcome.New, (await bed.FileAsync(run.Id, "marta.demo/e-video.mp4")).Outcome, "Per i video vale solo lo SHA-256."); + } + + [TestMethod] + public async Task AFileAlbertoDeletedIsNotBroughtBack() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var photo = ImportTestFiles.Photo(60); + var (_, saved) = await bed.AccountWithPhotoAsync("marta.demo", "900", photo); + await new LibraryDeletion(bed.Library.Db, bed.Library.Layout, bed.Library.Journal, bed.Library.Clock).DeleteAsync(saved.Entry.Id); + bed.Write("marta.demo/eliminata.jpg", photo); + + var run = await bed.AnalyzeAsync(); + + var file = (await bed.FilesAsync(run.Id)).Single(); + Assert.AreEqual(ImportOutcome.AlreadyInLibrary, file.Outcome); + StringAssert.Contains(file.LastError, "eliminato"); + } + + private sealed class SyncProgress(Action report) : IProgress + { + public void Report(ImportProgress value) => report(value); + } +} diff --git a/tests/Febe.Tests/Import/ImportCopyTests.cs b/tests/Febe.Tests/Import/ImportCopyTests.cs new file mode 100644 index 0000000..4c4f0e9 --- /dev/null +++ b/tests/Febe.Tests/Import/ImportCopyTests.cs @@ -0,0 +1,520 @@ +using System.Security.Cryptography; +using Febe.Core.Domain; +using Febe.Core.Import; +using Febe.Core.Library; +using Febe.Tests.Import.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Import; + +[TestClass] +public sealed class ImportCopyTests +{ + [TestMethod] + public async Task KnownFilesTakeTheLibraryNameAndTheOthersGoToImportati() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var marta = await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo")); + bed.Write("marta.demo/post/2026/2026-10-10_18-22-05_DBx3kQ2_1.jpg", ImportTestFiles.Photo(1)); + bed.Write("marta.demo/post/2026/2026-10-10_18-22-05_DBx3kQ2_2.jpg", ImportTestFiles.Photo(2)); + bed.Write("marta.demo/storie/2026/2026-10-13_09-41-07_3742118_1.mp4", ImportTestFiles.Mp4(null, payloadSeed: 11)); + bed.Write("marta.demo/IMG_20210506_070809.jpg", ImportTestFiles.Photo(3)); + bed.Write("marta.demo/senza data.jpg", ImportTestFiles.Photo(4), new DateTime(2018, 3, 4, 5, 6, 7, DateTimeKind.Utc)); + var folder = bed.Library.Layout.AccountFolder(marta); + Directory.CreateDirectory(Path.Combine(folder, "importati")); + var squatter = Path.Combine(folder, "importati", "IMG_20210506_070809.jpg"); + File.WriteAllBytes(squatter, [9, 9, 9]); + var before = bed.Fingerprint(); + + var run = await bed.AnalyzeAsync(); + await bed.Copier.CopyAsync(run.Id); + + CollectionAssert.AreEqual(before.ToList(), bed.Fingerprint().ToList(), "Con «Copia» gli originali restano come sono."); + var files = await bed.FilesAsync(run.Id); + Assert.IsTrue(files.All(f => f.State == ImportFileState.Copied), string.Join("; ", files.Select(f => f.RelativePath + ": " + f.State + " " + f.LastError))); + Assert.AreEqual(ImportRunState.Completed, (await bed.Library.Db.Imports.GetRunAsync(run.Id))!.State); + + var carousel = await bed.Library.Db.Imports.FindEntryByCodeAsync(marta.Id, EntryKind.Post, "DBx3kQ2"); + var post = (await bed.Library.Db.Entries.GetWithMediaAsync(carousel!.Id))!; + Assert.AreEqual(Provenance.Imported, post.Entry.Provenance); + Assert.AreEqual(EntryState.Imported, post.Entry.State); + Assert.AreEqual(new DateTimeOffset(2026, 10, 10, 16, 22, 5, TimeSpan.Zero), post.Entry.PublishedAt); + CollectionAssert.AreEqual( + new[] { "post/2026/2026-10-10_18-22-05_DBx3kQ2_1.jpg", "post/2026/2026-10-10_18-22-05_DBx3kQ2_2.jpg" }, + post.Media.Select(m => m.RelativePath).ToArray(), + "Un post con più file diventa un elemento solo, con i nomi dello schema."); + Assert.IsTrue(post.Media.All(m => m.State == MediaState.Imported && m.HasThumbnail && m.PerceptualHash is not null)); + Assert.IsTrue(bed.Library.Index.Count >= 2, "Le impronte delle foto importate entrano nell'indice."); + Assert.AreEqual(post.Entry.PublishedAt.UtcDateTime, File.GetLastWriteTimeUtc(bed.Library.Layout.FullPath(marta, post.Media[0].RelativePath!))); + + var story = (await bed.Library.Db.Entries.FindAsync(marta.Id, EntryKind.Story, "3742118"))!; + Assert.AreEqual("storie/2026/2026-10-13_09-41-07_3742118_1.mp4", (await bed.Library.Db.Media.ListByEntryAsync(story.Id)).Single().RelativePath); + + var byDate = files.Single(f => f.RelativePath.EndsWith("IMG_20210506_070809.jpg", StringComparison.Ordinal)); + Assert.AreEqual("importati/IMG_20210506_070809 (2).jpg", byDate.DestinationPath, "Senza codice: in importati con il nome originale, e mai sopra un file che c'è già."); + CollectionAssert.AreEqual(new byte[] { 9, 9, 9 }, File.ReadAllBytes(squatter)); + Assert.AreEqual("importati/senza data.jpg", files.Single(f => f.RelativePath.EndsWith("senza data.jpg", StringComparison.Ordinal)).DestinationPath); + + var journal = await AccountJournal.ReadAsync(folder); + Assert.IsTrue(journal.Lines.All(l => l.Entry.Provenance == "imported")); + Assert.AreEqual(4, journal.Lines.Select(l => l.Entry.Id ?? l.Entry.Code ?? l.Files![0].Path).Distinct().Count(), "Una riga di _febe.jsonl per ogni elemento importato."); + } + + [TestMethod] + public async Task AFolderWithoutAccountBlocksOnlyItsOwnFiles() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + bed.Write("marta.demo/a.jpg", ImportTestFiles.Photo(10)); + bed.Write("marta.demo/b.jpg", ImportTestFiles.Photo(11)); + bed.Write("Foto sparse/c.jpg", ImportTestFiles.Photo(12)); + bed.Write("Foto sparse/d.jpg", ImportTestFiles.Photo(13)); + bed.Write("Foto sparse/e.jpg", ImportTestFiles.Photo(14)); + var run = await bed.AnalyzeAsync(); + + var plan = await bed.Review.GetPlanAsync(run.Id); + Assert.AreEqual(2, plan.ToImport); + Assert.AreEqual(3, plan.LeftOutNoAccount); + Assert.AreEqual(1, plan.FoldersWithoutAccount); + Assert.AreEqual("Importa 2 file", plan.ButtonLabel); + Assert.AreEqual("1 cartella senza account: 3 file restano fuori", plan.LeftOutLabel); + + await bed.Copier.CopyAsync(run.Id); + + var created = await bed.Library.Db.Accounts.FindByUsernameAsync("marta.demo"); + Assert.IsNotNull(created, "L'account nuovo nasce quando parte la copia."); + Assert.AreEqual(AccountState.ArchiveOnly, created.State); + Assert.IsFalse(created.KeepUpdated); + var files = await bed.FilesAsync(run.Id); + Assert.AreEqual(2, files.Count(f => f.State == ImportFileState.Copied)); + var left = files.Where(f => f.Folder == "Foto sparse").ToList(); + Assert.IsTrue(left.All(f => f.State == ImportFileState.Analyzed && f.LastError == ImportText.NoteNoAccount)); + var report = await bed.Reports.GetReportAsync(run.Id); + Assert.AreEqual(2, report.Copied); + Assert.AreEqual(3, report.LeftOut); + + // «Importa i rimasti»: the folder gets an account and the copy runs again on the same import. + await bed.Review.SetFolderTargetAsync(run.Id, "Foto sparse", FolderTarget.Existing(created.Id)); + Assert.AreEqual(3, (await bed.Review.GetPlanAsync(run.Id)).ToImport); + await bed.Copier.CopyAsync(run.Id); + Assert.AreEqual(5, (await bed.FilesAsync(run.Id)).Count(f => f.State == ImportFileState.Copied)); + Assert.AreEqual(0, (await bed.Review.GetPlanAsync(run.Id)).ToImport); + Assert.IsNull((await bed.Review.GetPlanAsync(run.Id)).LeftOutLabel); + } + + [TestMethod] + public async Task AnInterruptedCopyResumesWithoutDuplicates() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + for (var i = 0; i < 20; i++) + { + bed.Write($"luca.demo/foto-{i:00}.png", ImportTestFiles.Png(200 + i, 48, 36)); + } + + var run = await bed.AnalyzeAsync(); + using var stop = new CancellationTokenSource(); + var progress = new SyncProgress(p => + { + if (p.Phase == ImportPhase.Copying && p.FilesDone >= 7) + { + stop.Cancel(); + } + }); + + await Assert.ThrowsAsync(() => bed.Copier.CopyAsync(run.Id, progress, stop.Token)); + Assert.AreEqual(ImportRunState.CopyInterrupted, (await bed.Library.Db.Imports.GetRunAsync(run.Id))!.State); + var halfway = (await bed.FilesAsync(run.Id)).Count(f => f.State == ImportFileState.Copied); + Assert.IsTrue(halfway is >= 7 and < 20, $"Copiati prima dell'interruzione: {halfway}."); + + await bed.Copier.CopyAsync(run.Id); + + var files = await bed.FilesAsync(run.Id); + Assert.IsTrue(files.All(f => f.State == ImportFileState.Copied)); + var account = (await bed.Library.Db.Accounts.FindByUsernameAsync("luca.demo"))!; + var onDisk = Directory.GetFiles(bed.Library.Layout.AccountFolder(account), "*.png", SearchOption.AllDirectories); + Assert.HasCount(20, onDisk, "Nessun file copiato due volte."); + Assert.IsFalse(onDisk.Any(f => f.Contains(" (2)", StringComparison.Ordinal))); + Assert.HasCount(20, await bed.Library.Db.Entries.ListByAccountAsync(account.Id)); + } + + [TestMethod] + public async Task MoveDeletesAnOriginalOnlyAfterItsCopyIsVerified() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var already = ImportTestFiles.Photo(30); + await bed.AccountWithPhotoAsync("marta.demo", "300", already); + var moved = bed.Write("marta.demo/nuova.jpg", ImportTestFiles.Photo(31)); + var skipped = bed.Write("marta.demo/gia-presente.jpg", already); + var run = await bed.AnalyzeAsync(); + await bed.Review.SetModeAsync(run.Id, ImportMode.Move); + + await bed.Copier.CopyAsync(run.Id); + + var file = await bed.FileAsync(run.Id, "marta.demo/nuova.jpg"); + Assert.AreEqual(ImportFileState.Moved, file.State); + Assert.IsFalse(File.Exists(moved), "Copia verificata: l'originale si elimina."); + var account = (await bed.Library.Db.Accounts.FindByUsernameAsync("marta.demo"))!; + var copy = bed.Library.Layout.FullPath(account, file.DestinationPath!); + Assert.AreEqual(file.Sha256, Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(copy)))); + Assert.IsTrue(File.Exists(skipped), "Un file saltato non si tocca, nemmeno con «Sposta»."); + CollectionAssert.AreEqual(new[] { moved }, bed.FileSystem.Deleted); + } + + [TestMethod] + public async Task MoveNeverDeletesAnUnverifiedOriginal() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var original = bed.Write("marta.demo/preziosa.jpg", ImportTestFiles.Photo(40)); + var originalBytes = File.ReadAllBytes(original); + var run = await bed.AnalyzeAsync(); + await bed.Review.SetModeAsync(run.Id, ImportMode.Move); + bed.FileSystem.CorruptCopies = true; // the copy on disk is damaged before it is checked + + await bed.Copier.CopyAsync(run.Id); + + var file = await bed.FileAsync(run.Id, "marta.demo/preziosa.jpg"); + Assert.AreEqual(ImportFileState.Failed, file.State); + Assert.AreEqual(ImportText.NoteNotVerified, file.LastError); + Assert.IsTrue(File.Exists(original), "Copia non verificata: l'originale resta."); + CollectionAssert.AreEqual(originalBytes, File.ReadAllBytes(original)); + Assert.IsEmpty(bed.FileSystem.Deleted); + + // Trying again checks the copy again: still damaged, still kept. + await bed.Copier.CopyAsync(run.Id); + Assert.IsTrue(File.Exists(original)); + Assert.IsEmpty(bed.FileSystem.Deleted); + } + + [TestMethod] + public async Task AMoveLeftHalfwayIsFinishedAndCopiesMadeBeforeAreNeverMoved() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var copiedFirst = bed.Write("marta.demo/copiata-prima.jpg", ImportTestFiles.Photo(45)); + var locked = bed.Write("Foto sparse/in-uso.jpg", ImportTestFiles.Photo(46)); + var run = await bed.AnalyzeAsync(); + + // First «Copia» for marta.demo only (Foto sparse has no account yet). + await bed.Copier.CopyAsync(run.Id); + Assert.AreEqual(ImportFileState.Copied, (await bed.FileAsync(run.Id, "marta.demo/copiata-prima.jpg")).State); + + // Then «Sposta» for the rest, with the original open in another program. + var marta = (await bed.Library.Db.Accounts.FindByUsernameAsync("marta.demo"))!; + await bed.Review.SetFolderTargetAsync(run.Id, "Foto sparse", FolderTarget.Existing(marta.Id)); + await bed.Review.SetModeAsync(run.Id, ImportMode.Move); + bed.FileSystem.FailDeletes = true; + await bed.Copier.CopyAsync(run.Id); + var stuck = await bed.FileAsync(run.Id, "Foto sparse/in-uso.jpg"); + Assert.AreEqual(ImportFileState.Copied, stuck.State); + StringAssert.EndsWith(stuck.LastError, ImportText.NoteOriginalKept); + Assert.IsTrue(File.Exists(locked)); + + bed.FileSystem.FailDeletes = false; + await bed.Copier.CopyAsync(run.Id); + + Assert.AreEqual(ImportFileState.Moved, (await bed.FileAsync(run.Id, "Foto sparse/in-uso.jpg")).State); + Assert.IsNull((await bed.FileAsync(run.Id, "Foto sparse/in-uso.jpg")).LastError); + Assert.IsFalse(File.Exists(locked), "La copia è verificata di nuovo, poi l'originale si elimina."); + Assert.IsTrue(File.Exists(copiedFirst), "Un file copiato con «Copia» non si elimina passando a «Sposta»."); + Assert.AreEqual(ImportFileState.Copied, (await bed.FileAsync(run.Id, "marta.demo/copiata-prima.jpg")).State); + } + + [TestMethod] + public async Task AFileChangedAfterTheAnalysisIsNotCopied() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var path = bed.Write("marta.demo/cambiata.jpg", ImportTestFiles.Photo(47)); + var run = await bed.AnalyzeAsync(); + File.WriteAllBytes(path, ImportTestFiles.Photo(48)); + + await bed.Copier.CopyAsync(run.Id); + + var file = (await bed.FilesAsync(run.Id)).Single(); + Assert.AreEqual(ImportFileState.Failed, file.State); + Assert.AreEqual(ImportText.NoteChanged, file.LastError); + var account = (await bed.Library.Db.Accounts.FindByUsernameAsync("marta.demo"))!; + Assert.IsEmpty(await bed.Library.Db.Entries.ListByAccountAsync(account.Id), "Nessun elemento vuoto resta in libreria."); + Assert.IsFalse(Directory.Exists(bed.Library.Layout.AccountFolder(account)) && Directory.EnumerateFiles(bed.Library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories).Any()); + } + + [TestMethod] + public async Task AnImportCompletesASeriesAlreadyInTheLibrary() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var marta = await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var first = ImportTestFiles.Photo(130); + var entry = Make.Entry(marta.Id, "555", new DateTimeOffset(2026, 10, 10, 16, 22, 5, TimeSpan.Zero)) with { Code = "SER1234" }; + var added = await bed.Library.Db.Entries.AddAsync(entry, [Make.Photo(1), Make.Photo(2)]); + await bed.Library.Ingest.SaveMediaAsync(marta, added.Stored.Entry, added.Stored.Media[0], new MediaContent { Content = new MemoryStream(first), Extension = ".jpg" }); + bed.Write("marta.demo/post/2026/2026-10-10_18-22-05_SER1234_1.jpg", first); + bed.Write("marta.demo/post/2026/2026-10-10_18-22-05_SER1234_2.jpg", ImportTestFiles.Photo(131)); + + var run = await bed.AnalyzeAsync(); + Assert.AreEqual(ImportOutcome.AlreadyInLibrary, (await bed.FileAsync(run.Id, "marta.demo/post/2026/2026-10-10_18-22-05_SER1234_1.jpg")).Outcome); + Assert.AreEqual(ImportOutcome.New, (await bed.FileAsync(run.Id, "marta.demo/post/2026/2026-10-10_18-22-05_SER1234_2.jpg")).Outcome, "Il secondo file manca: non è un doppione."); + await bed.Copier.CopyAsync(run.Id); + + var stored = (await bed.Library.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!; + Assert.AreEqual(EntryState.Downloaded, stored.Entry.State, "L'elemento ora ha tutti i suoi file."); + Assert.AreEqual("post/2026/2026-10-10_18-22-05_SER1234_2.jpg", stored.Media[1].RelativePath); + Assert.IsTrue(EntryStateRules.IsPresent(stored.Media[1].State)); + Assert.HasCount(1, await bed.Library.Db.Entries.ListByAccountAsync(marta.Id), "Nessun elemento nuovo: il file completa quello che c'era."); + } + + [TestMethod] + public async Task AReadOnlySourceDoesNotOfferMove() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp, readOnlySource: true); + bed.Write("marta.demo/a.jpg", ImportTestFiles.Photo(50)); + var info = bed.Environment.CreateSources().Inspect(bed.Source); + Assert.IsTrue(info.ReadOnly); + Assert.IsFalse(info.CanMove); + + var run = await bed.AnalyzeAsync(); + Assert.IsTrue(run.SourceReadOnly); + Assert.IsFalse((await bed.Review.GetSummaryAsync(run.Id)).CanMove, "«Sposta» non compare."); + await Assert.ThrowsAsync(() => bed.Review.SetModeAsync(run.Id, ImportMode.Move)); + + await bed.Copier.CopyAsync(run.Id); + Assert.AreEqual(ImportFileState.Copied, (await bed.FilesAsync(run.Id)).Single().State); + Assert.IsTrue(File.Exists(Path.Combine(bed.Source, "marta.demo", "a.jpg"))); + + // In Docker the /importa volume is read-only by configuration, whatever the probe says. + var docker = new ImportSources(ImportSourceOptions.Docker(bed.Temp.Path), probe: new FixedAccessProbe(false)); + Assert.IsTrue(docker.Inspect(bed.Source).ReadOnly); + } + + [TestMethod] + public async Task DecisionsOnProbableDuplicatesAreAppliedByTheCopyOnly() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var (marta, a) = await bed.AccountWithPhotoAsync("marta.demo", "70", ImportTestFiles.Photo(70, 800, 600, 92)); + var (_, b) = await bed.AccountWithPhotoAsync("marta.demo", "71", ImportTestFiles.Resized(71, 800, 600, 400, 300, 70)); + var (_, c) = await bed.AccountWithPhotoAsync("marta.demo", "72", ImportTestFiles.Photo(72, 800, 600, 92)); + var (_, d) = await bed.AccountWithPhotoAsync("marta.demo", "73", ImportTestFiles.Photo(73, 800, 600, 92)); + bed.Write("marta.demo/a-piccola.jpg", ImportTestFiles.Resized(70, 800, 600, 400, 300, 60)); + var bigger = bed.Write("marta.demo/b-grande.jpg", ImportTestFiles.Photo(71, 800, 600, 92)); + bed.Write("marta.demo/c-piccola.jpg", ImportTestFiles.Resized(72, 800, 600, 400, 300, 60)); + bed.Write("marta.demo/d-piccola.jpg", ImportTestFiles.Resized(73, 800, 600, 400, 300, 60)); + var run = await bed.AnalyzeAsync(); + var oldB = bed.Library.Layout.FullPath(marta, b.Media[0].RelativePath!); + + var undecided = await bed.Review.GetPlanAsync(run.Id); + Assert.AreEqual(4, undecided.LeftOutUndecided); + StringAssert.Contains(undecided.LeftOutLabel, "4 file aspettano la tua decisione"); + await bed.Copier.CopyAsync(run.Id); + Assert.IsTrue(File.Exists(oldB), "Senza una scelta di Alberto non si sostituisce nulla (regola 12)."); + Assert.IsTrue((await bed.FilesAsync(run.Id)).All(f => f.State == ImportFileState.Analyzed)); + + var cases = await bed.Review.ListDuplicatesAsync(run.Id); + Assert.HasCount(4, cases); + Assert.IsTrue(cases.All(x => x.Pair.Decision == DuplicateDecision.Pending), "Nessuna scelta fatta in partenza."); + DuplicateCase Case(EntryWithMedia library) => cases.Single(x => x.Existing.MediaId == library.Media[0].Id); + Assert.IsTrue(Case(b).CandidateIsLarger); + Assert.IsFalse(Case(a).CandidateIsLarger); + await bed.Review.DecideAsync(run.Id, Case(a).Pair.Id, DuplicateDecision.KeepLarger); + await bed.Review.DecideAsync(run.Id, Case(b).Pair.Id, DuplicateDecision.KeepLarger); + await bed.Review.DecideAsync(run.Id, Case(c).Pair.Id, DuplicateDecision.KeepBoth); + await bed.Review.DecideAsync(run.Id, Case(d).Pair.Id, DuplicateDecision.KeepExisting); + var plan = await bed.Review.GetPlanAsync(run.Id); + Assert.AreEqual(2, plan.ToImport); + Assert.AreEqual(1, plan.ToReplace); + + await bed.Copier.CopyAsync(run.Id); + + var files = await bed.FilesAsync(run.Id); + ImportFile File_(string name) => files.Single(f => f.RelativePath == "marta.demo/" + name); + Assert.AreEqual(ImportFileState.Skipped, File_("a-piccola.jpg").State); + Assert.AreEqual(ImportText.NoteLibraryLarger, File_("a-piccola.jpg").LastError); + Assert.AreEqual(ImportFileState.Skipped, File_("d-piccola.jpg").State); + Assert.AreEqual(ImportFileState.Copied, File_("c-piccola.jpg").State, "«Tienili entrambi»."); + Assert.AreEqual(1, (await bed.Library.Db.Entries.ListByAccountAsync(marta.Id)).Count(e => e.Provenance == Provenance.Imported), "Solo «Tienili entrambi» crea un elemento nuovo."); + + // «Tieni il più grande» with the imported file larger: the library file is replaced, safely. + var replaced = File_("b-grande.jpg"); + Assert.AreEqual(ImportFileState.Copied, replaced.State); + StringAssert.StartsWith(replaced.LastError, ImportText.NoteReplaced); + var media = (await bed.Library.Db.Media.GetAsync(b.Media[0].Id))!; + Assert.AreEqual(replaced.Sha256, media.Sha256, "Il record della libreria punta al file nuovo."); + Assert.AreEqual((800, 600), (media.Width, media.Height)); + Assert.AreEqual(MediaState.Downloaded, media.State, "Il file resta quello dell'elemento scaricato."); + var newPath = bed.Library.Layout.FullPath(marta, media.RelativePath!); + Assert.AreEqual(replaced.Sha256, Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(newPath)))); + Assert.IsFalse(File.Exists(oldB), "Il file più piccolo si elimina solo dopo che il nuovo è stato scritto e verificato."); + Assert.IsTrue(File.Exists(bigger), "Con «Copia» l'originale resta."); + Assert.IsTrue(bed.Library.Thumbnails.Exists(media.Sha256!)); + Assert.IsFalse(bed.Library.Thumbnails.Exists(b.Media[0].Sha256!), "La miniatura del file sostituito non serve più."); + var journal = await AccountJournal.ReadAsync(bed.Library.Layout.AccountFolder(marta)); + Assert.AreEqual(media.RelativePath, journal.Lines.Last(l => l.Entry.Id == "71").Files!.Single().Path, "L'ultima riga di _febe.jsonl porta il file nuovo."); + Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import)); + } + + [TestMethod] + public async Task ADecisionCanBeAppliedToTheOtherCases() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + for (var i = 0; i < 3; i++) + { + await bed.AccountWithPhotoAsync("marta.demo", (80 + i).ToString(System.Globalization.CultureInfo.InvariantCulture), ImportTestFiles.Photo(80 + i, 800, 600, 92)); + bed.Write($"marta.demo/copia-{i}.jpg", ImportTestFiles.Resized(80 + i, 800, 600, 400, 300, 60)); + } + + var account = (await bed.Library.Db.Accounts.FindByUsernameAsync("marta.demo"))!; + var story = Make.Entry(account.Id, "3742119", Make.T0, EntryKind.Story); + await bed.Library.SaveAsync(account, story, [new TestFile(Make.Photo(1), ImportTestFiles.Photo(90), ".jpg")]); + bed.Write("marta.demo/storie/2026/2026-10-13_10-00-00_3742119_1.jpg", ImportTestFiles.Photo(91)); + var run = await bed.AnalyzeAsync(); + var cases = await bed.Review.ListDuplicatesAsync(run.Id); + Assert.HasCount(4, cases); + + var visual = cases.First(c => c.Pair.Reason == DuplicateReason.VisuallySimilar); + Assert.AreEqual(3, await bed.Review.DecideAsync(run.Id, visual.Pair.Id, DuplicateDecision.KeepExisting, DecisionScope.SameReason)); + Assert.HasCount(1, await bed.Review.ListDuplicatesAsync(run.Id), "Resta il caso con un'altra ragione."); + + var last = (await bed.Review.ListDuplicatesAsync(run.Id)).Single(); + Assert.AreEqual(1, await bed.Review.DecideAsync(run.Id, last.Pair.Id, DuplicateDecision.KeepBoth, DecisionScope.AllPending)); + Assert.IsEmpty(await bed.Review.ListDuplicatesAsync(run.Id)); + Assert.AreEqual(ImportDecision.KeepExisting, (await bed.FileAsync(run.Id, "marta.demo/copia-1.jpg")).Decision); + await Assert.ThrowsAsync(() => bed.Review.DecideAsync(run.Id, last.Pair.Id, DuplicateDecision.Pending)); + } + + [TestMethod] + public async Task InsideTheSourceKeepLargerImportsOnlyTheLargest() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + bed.Write("marta.demo/1-media.jpg", ImportTestFiles.Resized(95, 800, 600, 600, 450, 80)); + bed.Write("marta.demo/2-grande.jpg", ImportTestFiles.Photo(95, 800, 600, 92)); + bed.Write("marta.demo/3-piccola.jpg", ImportTestFiles.Resized(95, 800, 600, 400, 300, 60)); + var run = await bed.AnalyzeAsync(); + var cases = await bed.Review.ListDuplicatesAsync(run.Id); + Assert.HasCount(2, cases); + Assert.IsTrue(cases.All(c => c.InsideSource)); + + await bed.Review.DecideAsync(run.Id, cases[0].Pair.Id, DuplicateDecision.KeepLarger, DecisionScope.AllPending); + await bed.Copier.CopyAsync(run.Id); + + var files = await bed.FilesAsync(run.Id); + Assert.AreEqual("marta.demo/2-grande.jpg", files.Single(f => f.State == ImportFileState.Copied).RelativePath); + Assert.AreEqual(2, files.Count(f => f.State == ImportFileState.Skipped)); + } + + [TestMethod] + public async Task AFebeLibraryIsImportedWithItsIdentifiersAndCaptions() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var folder = Path.Combine(bed.Source, "marta.demo"); + bed.Write("marta.demo/post/2025/2025-03-01_10-30-15_CxYz123_1.jpg", ImportTestFiles.Photo(100)); + bed.Write("marta.demo/evidenza/Estate 2025/2025-08-02_10-11-12_3391207_1.jpg", ImportTestFiles.Photo(101)); + await AccountJournal.AppendAsync(folder, new JournalLine + { + Op = JournalOps.Save, + At = Make.T0, + Account = new JournalAccount("4242", "marta.demo"), + Entry = new JournalEntry { Kind = "post", Id = "3100000000000000001", Code = "CxYz123", PublishedAt = new DateTimeOffset(2025, 3, 1, 9, 30, 15, 250, TimeSpan.Zero), Caption = "Al mare" }, + Files = [new JournalFile { N = 1, Type = "photo", Path = "post/2025/2025-03-01_10-30-15_CxYz123_1.jpg", Id = "3100000000000000002" }], + }); + await AccountJournal.AppendAsync(folder, new JournalLine + { + Op = JournalOps.Save, + At = Make.T0, + Account = new JournalAccount("4242", "marta.demo"), + Entry = new JournalEntry { Kind = "evidenza", Id = "3391207", PublishedAt = new DateTimeOffset(2025, 8, 2, 8, 11, 12, TimeSpan.Zero), Highlights = [new JournalHighlight("99", "Estate 2025")] }, + Files = [new JournalFile { N = 1, Type = "photo", Path = "evidenza/Estate 2025/2025-08-02_10-11-12_3391207_1.jpg" }], + }); + var marta = await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo", "4242")); + var info = bed.Environment.CreateSources().Inspect(bed.Source); + Assert.IsTrue(info.LooksLikeFebeLibrary); + + var run = await bed.AnalyzeAsync(); + var summary = await bed.Review.GetSummaryAsync(run.Id); + Assert.AreEqual(2, summary.Recognized, "Elementi di cui si conosce codice o identificativo: Febe non li riscaricherà."); + Assert.AreEqual(marta.Id, summary.Folders.Single().Target.AccountId, "Riconosciuto dall'identificativo Instagram dell'account."); + await bed.Copier.CopyAsync(run.Id); + + var post = (await bed.Library.Db.Entries.FindAsync(marta.Id, EntryKind.Post, "3100000000000000001"))!; + Assert.AreEqual("CxYz123", post.Code); + Assert.AreEqual("Al mare", post.Caption); + Assert.AreEqual(new DateTimeOffset(2025, 3, 1, 9, 30, 15, 250, TimeSpan.Zero), post.PublishedAt, "Data esatta dal giornale di Febe."); + Assert.AreEqual("3100000000000000002", (await bed.Library.Db.Media.ListByEntryAsync(post.Id)).Single().InstagramId); + Assert.IsTrue(await bed.Library.Db.Entries.IsKnownAsync(marta.Id, EntryKind.Post, "3100000000000000001"), "Quando terrà aggiornato l'account non lo riscaricherà."); + + var highlight = (await bed.Library.Db.Entries.FindAsync(marta.Id, EntryKind.Highlight, "3391207"))!; + var collections = await bed.Library.Db.Highlights.ListForEntryAsync(highlight.Id); + Assert.AreEqual("Estate 2025", collections.Single().Title); + Assert.AreEqual("evidenza/Estate 2025/2025-08-02_10-11-12_3391207_1.jpg", (await bed.Library.Db.Media.ListByEntryAsync(highlight.Id)).Single().RelativePath); + } + + [TestMethod] + public async Task TheCsvHasOneRowPerFileSemicolonsAndABom() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo")); + bed.Write("marta.demo/uno;due.jpg", ImportTestFiles.Photo(110)); + bed.Write("marta.demo/=SOMMA(1).jpg", ImportTestFiles.Photo(111)); + bed.Write("marta.demo/nota.txt", "testo"u8.ToArray()); + var run = await bed.AnalyzeAsync(); + await bed.Copier.CopyAsync(run.Id); + + using var output = new MemoryStream(); + await bed.Reports.WriteCsvAsync(run.Id, output); + var bytes = output.ToArray(); + + CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3], "UTF-8 con BOM, per Excel in italiano."); + var text = System.Text.Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3); + var lines = text.Split("\r\n", StringSplitOptions.RemoveEmptyEntries); + Assert.HasCount(4, lines, "Intestazione e una riga per file."); + Assert.AreEqual("File;Cartella;Esito;Stato;Account di destinazione;Tipo;Data;Origine della data;Formato;Byte;Larghezza;Altezza;Durata (s);SHA-256;Codice;Identificativo Instagram;Già in libreria;Destinazione;Nota", lines[0]); + Assert.IsTrue(lines.Any(l => l.StartsWith("\"marta.demo/uno;due.jpg\";marta.demo;Nuovo;Copiato;marta.demo;", StringComparison.Ordinal)), "Un campo con «;» va tra virgolette."); + Assert.IsTrue(lines.Any(l => l.StartsWith("marta.demo/=SOMMA(1).jpg;", StringComparison.Ordinal)), "Il percorso comincia con la cartella: nessuna formula."); + Assert.IsTrue(lines.Any(l => l.Contains(";Non riconosciuto;Saltato;", StringComparison.Ordinal))); + Assert.AreEqual("'=SOMMA(1)", ImportReports.Field("=SOMMA(1)"), "Un testo che Excel prenderebbe per una formula."); + Assert.AreEqual("\"a \"\"b\"\"\"", ImportReports.Field("a \"b\"")); + Assert.AreEqual($"importazione-2026-10-13-{run.Id}.csv", bed.Reports.CsvFileName(run)); + } + + [TestMethod] + public async Task TheReportCountsEveryOutcome() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var photo = ImportTestFiles.Photo(120); + await bed.AccountWithPhotoAsync("luca.demo", "120", photo); + await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo")); + bed.Write("marta.demo/gia.jpg", photo); + bed.Write("marta.demo/nuova.jpg", ImportTestFiles.Photo(121)); + bed.Write("marta.demo/copia/nuova.jpg", ImportTestFiles.Photo(121)); + bed.Write("marta.demo/documento.pdf", "%PDF-1.7\n"u8.ToArray()); + var run = await bed.AnalyzeAsync(); + await bed.Copier.CopyAsync(run.Id); + + var report = await bed.Reports.GetReportAsync(run.Id); + + Assert.AreEqual(4, report.Files); + Assert.AreEqual(1, report.ByOutcome[ImportOutcome.AlreadyInLibrary]); + Assert.AreEqual(1, report.ByOutcome[ImportOutcome.IdenticalInSource]); + Assert.AreEqual(1, report.Copied); + Assert.AreEqual(3, report.Skipped, "Già in libreria, copia identica e non riconosciuto."); + Assert.AreEqual("luca.demo", report.AlreadyInLibraryByAccount.Single().Username); + Assert.AreEqual("marta.demo", report.ImportedByAccount.Single().Username); + CollectionAssert.AreEqual(new[] { "marta.demo/documento.pdf" }, report.Unrecognized.ToArray()); + } + + private sealed class SyncProgress(Action report) : IProgress + { + public void Report(ImportProgress value) => report(value); + } +} diff --git a/tests/Febe.Tests/Import/ImportServiceTests.cs b/tests/Febe.Tests/Import/ImportServiceTests.cs new file mode 100644 index 0000000..9c88d8a --- /dev/null +++ b/tests/Febe.Tests/Import/ImportServiceTests.cs @@ -0,0 +1,123 @@ +using System.Collections.Concurrent; +using Febe.Core.Domain; +using Febe.Core.Import; +using Febe.Tests.Import.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Import; + +[TestClass] +public sealed class ImportServiceTests +{ + [TestMethod] + public async Task TheFourStepsRunInTheBackground() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo")); + for (var i = 0; i < 5; i++) + { + bed.Write($"marta.demo/foto-{i}.jpg", ImportTestFiles.Photo(300 + i, 200, 150)); + } + + await using var service = new ImportService(bed.Environment); + var events = new ConcurrentQueue(); + service.ProgressChanged += (_, p) => events.Enqueue(p); + + var source = service.InspectSource(bed.Source); + Assert.IsTrue(source.CanMove); + var run = await service.StartAsync(bed.Source); + Assert.AreEqual(ImportRunState.Analyzing, run.State); + await Assert.ThrowsAsync(() => service.StartAsync(bed.Source), "Un lavoro alla volta."); + + var analysed = await service.WaitAsync(run.Id); + Assert.AreEqual(ImportRunState.Reviewing, analysed!.State); + Assert.IsNull(service.ActiveRunId); + Assert.IsTrue(events.Any(e => e.Phase == ImportPhase.Finished && e.RunId == run.Id && e.FilesDone == 5)); + + var review = await service.GetReviewAsync(run.Id); + Assert.AreEqual(5, review.ByOutcome[ImportOutcome.New]); + var plan = await service.GetPlanAsync(run.Id); + Assert.AreEqual("Importa 5 file", plan.ButtonLabel); + + await service.StartCopyAsync(run.Id, ImportMode.Copy); + var copied = await service.WaitAsync(run.Id); + Assert.AreEqual(ImportRunState.Completed, copied!.State); + var progress = await service.GetProgressAsync(run.Id); + Assert.AreEqual(ImportPhase.Finished, progress.Phase); + Assert.AreEqual(5, progress.Copied); + Assert.AreEqual(5, (await service.GetReportAsync(run.Id)).Copied); + } + + [TestMethod] + public async Task AJobLeftRunningByAStopIsResumed() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + bed.Write("marta.demo/a.jpg", ImportTestFiles.Photo(310, 200, 150)); + var run = await bed.Analyzer.CreateRunAsync(bed.Environment.CreateSources().Inspect(bed.Source)); + + // Febe stopped while the analysis was running: the state says «in corso» but nothing runs. + await using var service = new ImportService(bed.Environment); + Assert.AreEqual(1, await service.RecoverAsync()); + Assert.AreEqual(ImportRunState.AnalysisInterrupted, (await service.GetRunAsync(run.Id))!.State); + + await service.ResumeAsync(run.Id); + Assert.AreEqual(ImportRunState.Reviewing, (await service.WaitAsync(run.Id))!.State); + await Assert.ThrowsAsync(() => service.ResumeAsync(run.Id), "Niente da riprendere."); + } + + [TestMethod] + public async Task InterruptStopsTheJobAndKeepsWhatIsDone() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + for (var i = 0; i < 100; i++) + { + bed.Write($"marta.demo/f{i:000}.png", ImportTestFiles.Png(400 + i, 40, 30)); + } + + // Files from f080 on cannot be read until the job is stopped: the first group of 64 is done by then. + var gated = new GatedFileSystem(bed.FileSystem, path => string.CompareOrdinal(Path.GetFileName(path), "f080.png") >= 0); + await using var service = new ImportService(bed.Environment with { FileSystem = gated }); + var run = await service.StartAsync(bed.Source); + await gated.Reached.Task.WaitAsync(TimeSpan.FromSeconds(60)); + await service.InterruptAsync(run.Id); + + var stopped = (await service.GetRunAsync(run.Id))!; + Assert.AreEqual(ImportRunState.AnalysisInterrupted, stopped.State); + Assert.IsNull(stopped.LastError); + var summary = await bed.Library.Db.Imports.GetSummaryAsync(run.Id); + Assert.AreEqual(64, summary.ByState[ImportFileState.Analyzed]); + Assert.AreEqual(36, summary.ByState[ImportFileState.Pending]); + var progress = await service.GetProgressAsync(run.Id); + Assert.AreEqual((64, 100), (progress.FilesDone, progress.FilesTotal)); + + await using var again = new ImportService(bed.Environment); + await again.ResumeAsync(run.Id); + Assert.AreEqual(ImportRunState.Reviewing, (await again.WaitAsync(run.Id))!.State); + Assert.AreEqual(100, (await bed.Library.Db.Imports.GetSummaryAsync(run.Id)).ByState[ImportFileState.Analyzed]); + } + + [TestMethod] + public async Task DiscardingAnImportLeavesFilesAlone() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + await bed.AccountWithPhotoAsync("marta.demo", "1", ImportTestFiles.Photo(320, 800, 600, 92)); + bed.Write("marta.demo/simile.jpg", ImportTestFiles.Resized(320, 800, 600, 400, 300, 60)); + var before = bed.Fingerprint(); + await using var service = new ImportService(bed.Environment); + var run = await service.StartAsync(bed.Source, new ImportAnalysisOptions { StogramHypothesis = true }); + await service.WaitAsync(run.Id); + Assert.AreEqual(1, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import)); + Assert.IsTrue((await service.GetReviewAsync(run.Id)).StogramHypothesis); + + await service.DiscardAsync(run.Id); + + Assert.IsNull(await service.GetRunAsync(run.Id), "Nulla era stato copiato: l'importazione sparisce."); + Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import)); + Assert.IsNull(await bed.Library.Db.Settings.GetAsync($"importazione.{run.Id}.ipotesi-stogram")); + CollectionAssert.AreEqual(before.ToList(), bed.Fingerprint().ToList()); + } +} diff --git a/tests/Febe.Tests/Import/ImportSourcesTests.cs b/tests/Febe.Tests/Import/ImportSourcesTests.cs new file mode 100644 index 0000000..24353b8 --- /dev/null +++ b/tests/Febe.Tests/Import/ImportSourcesTests.cs @@ -0,0 +1,81 @@ +using Febe.Core.Import; +using Febe.Core.Library; +using Febe.Tests.Import.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Import; + +[TestClass] +public sealed class ImportSourcesTests +{ + [TestMethod] + public void InDockerOnlyTheImportVolumeIsOffered() + { + using var temp = new TempFolder("sorgenti"); + var root = temp.Combine("importa"); + Directory.CreateDirectory(Path.Combine(root, "4K Stogram", "marta.demo")); + Directory.CreateDirectory(Path.Combine(root, "Telefono")); + Directory.CreateDirectory(temp.Combine("fuori")); + var sources = new ImportSources(ImportSourceOptions.Docker(root), probe: new FixedAccessProbe(false)); + + var choices = sources.Browse(); + CollectionAssert.AreEqual(new[] { "4K Stogram", "Telefono" }, choices.Select(c => c.Name).ToArray()); + Assert.IsTrue(choices[0].HasSubfolders); + Assert.AreEqual("4K Stogram/marta.demo", sources.Browse("4K Stogram").Single().Path); + + var info = sources.Inspect("4K Stogram"); + Assert.AreEqual(Path.Combine(root, "4K Stogram"), info.FullPath); + Assert.IsTrue(info.ReadOnly, "Il volume /importa è in sola lettura."); + Assert.IsFalse(info.CanMove); + Assert.AreEqual(root + "/4K Stogram", info.DisplayPath); + + var outside = Assert.ThrowsExactly(() => sources.Inspect(temp.Combine("fuori"))); + StringAssert.Contains(outside.Message, "sottocartella"); + Assert.ThrowsExactly(() => sources.Inspect("../fuori")); + Assert.ThrowsExactly(() => sources.Inspect("non-esiste")); + Assert.ThrowsExactly(() => sources.Browse("..")); + Assert.ThrowsExactly(() => sources.Inspect(" ")); + } + + [TestMethod] + public void TheLibraryAndTheDataFolderAreNotSources() + { + using var temp = new TempFolder("sorgenti"); + var library = temp.Combine("libreria"); + var data = temp.Combine("dati"); + Directory.CreateDirectory(Path.Combine(library, "marta.demo")); + File.WriteAllText(Path.Combine(library, "marta.demo", AccountJournal.FileName), string.Empty); + Directory.CreateDirectory(Path.Combine(library, "vecchie foto")); + Directory.CreateDirectory(data); + var sources = new ImportSources(ImportSourceOptions.AnyFolder, library, data, new FixedAccessProbe(false)); + + Assert.ThrowsExactly(() => sources.Inspect(temp.Path), "Contiene la libreria."); + Assert.ThrowsExactly(() => sources.Inspect(library)); + Assert.ThrowsExactly(() => sources.Inspect(Path.Combine(library, "marta.demo")), "Cartella di un account."); + Assert.ThrowsExactly(() => sources.Inspect(data)); + Assert.AreEqual("vecchie foto", sources.Inspect(Path.Combine(library, "vecchie foto")).Name, "Una cartella della libreria senza _febe.jsonl si può importare."); + } + + [TestMethod] + public void AReadOnlyMountIsSeenInTheMountTable() + { + const string mounts = """ + overlay / overlay rw,relatime,lowerdir=/x 0 0 + /dev/sdb1 /importa ext4 ro,relatime 0 0 + /dev/sdc1 /importa/scrivibile ext4 rw,relatime 0 0 + /dev/sdd1 /mnt/foto\040di\040casa xfs ro 0 0 + """; + Assert.IsTrue(SystemSourceAccessProbe.MountIsReadOnly(mounts, "/importa/4K Stogram")); + Assert.IsTrue(SystemSourceAccessProbe.MountIsReadOnly(mounts, "/importa")); + Assert.IsFalse(SystemSourceAccessProbe.MountIsReadOnly(mounts, "/importa/scrivibile/a"), "Vince il punto di montaggio più lungo."); + Assert.IsFalse(SystemSourceAccessProbe.MountIsReadOnly(mounts, "/home/alberto/Immagini")); + Assert.IsFalse(SystemSourceAccessProbe.MountIsReadOnly(mounts, "/importazione"), "/importa non contiene /importazione."); + Assert.IsTrue(SystemSourceAccessProbe.MountIsReadOnly(mounts, "/mnt/foto di casa/2019")); + + if (OperatingSystem.IsLinux()) + { + using var temp = new TempFolder("sorgenti"); + Assert.IsFalse(new SystemSourceAccessProbe().IsReadOnly(temp.Path), "Una cartella temporanea si può scrivere."); + } + } +} diff --git a/tests/Febe.Tests/Import/MediaReaderTests.cs b/tests/Febe.Tests/Import/MediaReaderTests.cs new file mode 100644 index 0000000..c660bde --- /dev/null +++ b/tests/Febe.Tests/Import/MediaReaderTests.cs @@ -0,0 +1,177 @@ +using System.Text; +using Febe.Core.Domain; +using Febe.Core.Import; +using Febe.Tests.Import.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Import; + +[TestClass] +public sealed class MediaReaderTests +{ + private static readonly DateTimeOffset Now = new(2026, 10, 13, 8, 0, 0, TimeSpan.Zero); + + [TestMethod] + public void TheTypeComesFromTheContentNotFromTheExtension() + { + var jpeg = ImportTestFiles.Photo(1, 64, 48); + var png = ImportTestFiles.Png(2, 64, 48); + Assert.AreEqual("image/jpeg", MediaSniffer.Detect(jpeg, ".png")?.ContentType, "Un JPEG chiamato .png resta un JPEG."); + Assert.AreEqual(".jpg", MediaSniffer.Detect(jpeg, ".jpeg")?.Extension); + Assert.AreEqual("image/png", MediaSniffer.Detect(png, ".jpg")?.ContentType); + Assert.AreEqual(MediaKind.Photo, MediaSniffer.Detect("GIF89a\x01\0\x01\0"u8.ToArray())?.Kind); + Assert.AreEqual("image/webp", MediaSniffer.Detect("RIFF\0\0\0\0WEBPVP8 "u8.ToArray())?.ContentType); + Assert.AreEqual("video/x-msvideo", MediaSniffer.Detect("RIFF\0\0\0\0AVI LIST"u8.ToArray())?.ContentType); + + Assert.AreEqual("image/heic", MediaSniffer.Detect(Ftyp("heic", "mif1", "heic"))?.ContentType); + Assert.AreEqual("image/heif", MediaSniffer.Detect(Ftyp("mif1", "mif1"))?.ContentType); + Assert.AreEqual("image/avif", MediaSniffer.Detect(Ftyp("avif", "mif1", "avif"))?.ContentType); + Assert.AreEqual("video/mp4", MediaSniffer.Detect(Ftyp("isom", "isom", "mp41"))?.ContentType); + Assert.AreEqual("video/mp4", MediaSniffer.Detect(Ftyp("mp42", "mp42"))?.ContentType); + Assert.AreEqual("video/quicktime", MediaSniffer.Detect(Ftyp("qt ", "qt "))?.ContentType); + Assert.AreEqual("video/quicktime", MediaSniffer.Detect(ImportTestFiles.Mp4(Now, withFtyp: false))?.ContentType, "MOV senza ftyp, che comincia con moov."); + Assert.AreEqual("video/webm", MediaSniffer.Detect([0x1A, 0x45, 0xDF, 0xA3, 0x9F, 0x42, 0x86, 0x81, 0x01, 0x42, 0x82, 0x84, .. "webm"u8])?.ContentType); + Assert.AreEqual(MediaKind.Photo, MediaSniffer.Detect("II*\0\x08\0\0\0"u8.ToArray(), ".DNG")?.Kind); + Assert.AreEqual(".dng", MediaSniffer.Detect("II*\0\x08\0\0\0"u8.ToArray(), ".DNG")?.Extension, "I formati raw tengono la loro estensione."); + + Assert.IsNull(MediaSniffer.Detect(Ftyp("M4A ", "M4A ", "mp42")), "Solo audio: né foto né video."); + Assert.IsNull(MediaSniffer.Detect(Encoding.UTF8.GetBytes("Appunti del viaggio, non una foto."))); + Assert.IsNull(MediaSniffer.Detect("%PDF-1.7\n"u8.ToArray())); + Assert.IsNull(MediaSniffer.Detect([])); + } + + [TestMethod] + public void TheShootingDateIsReadFromExifWrittenByHand() + { + var zone = TestZones.Rome; + var jpeg = ImportTestFiles.PhotoWithExifDate(3, new DateTime(2021, 5, 6, 7, 8, 9), width: 64, height: 48); + Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 5, 8, 9, TimeSpan.Zero), ExifDateReader.Read(jpeg, zone), "Ora locale di Roma (estate, +2)."); + + var withOffset = ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), ImportTestFiles.Tiff("2021:05:06 07:08:09", offsetOriginal: "-05:00", littleEndian: true)); + Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 12, 8, 9, TimeSpan.Zero), ExifDateReader.Read(withOffset, zone)?.ToUniversalTime(), "Il fuso scritto dalla fotocamera vince."); + + var onlyCreate = ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), ImportTestFiles.Tiff(null, createDate: "2019:12:31 23:59:58")); + Assert.AreEqual(new DateTimeOffset(2019, 12, 31, 22, 59, 58, TimeSpan.Zero), ExifDateReader.Read(onlyCreate, zone), "Senza DateTimeOriginal si usa CreateDate."); + + var png = ImportTestFiles.PngWithExif(ImportTestFiles.Png(4, 32, 24), ImportTestFiles.Tiff("2018:02:03 10:00:00")); + Assert.AreEqual(new DateTimeOffset(2018, 2, 3, 9, 0, 0, TimeSpan.Zero), ExifDateReader.Read(png, zone), "PNG con il blocco eXIf."); + + Assert.IsNull(ExifDateReader.Read(ImportTestFiles.Photo(3, 64, 48), zone), "Nessun EXIF: nessuna data."); + Assert.IsNull(ExifDateReader.Read(ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), ImportTestFiles.Tiff("0000:00:00 00:00:00")), zone)); + + // A damaged block (offsets beyond the end) gives no date, never an exception. + var damaged = ImportTestFiles.Tiff("2021:05:06 07:08:09"); + damaged.AsSpan(36, 4).Fill(0xFF); // the offset of the date value points far beyond the block + Assert.IsNull(ExifDateReader.Read(ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), damaged), zone)); + Assert.IsNull(ExifDateReader.Read(ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), damaged.AsSpan(0, 20).ToArray()), zone)); + } + + [TestMethod] + public void CreationTimeDurationAndSizeComeFromTheMp4Header() + { + var created = new DateTimeOffset(2022, 7, 1, 18, 30, 0, TimeSpan.Zero); + var info = Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(created, 1080, 1920, 15_500)), Now); + Assert.IsNotNull(info); + Assert.AreEqual(created, info.CreatedAt); + Assert.AreEqual(TimeSpan.FromMilliseconds(15_500), info.Duration); + Assert.AreEqual(1080, info.Width); + Assert.AreEqual(1920, info.Height); + + var atEnd = Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(created, moovAtEnd: true)), Now); + Assert.AreEqual(created, atEnd?.CreatedAt, "Il moov dopo i dati si trova saltando mdat."); + + var rotated = Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(created, 1920, 1080, rotated: true)), Now); + Assert.AreEqual((1080, 1920), (rotated?.Width, rotated?.Height), "Un video ruotato di 90° si mostra in verticale."); + + Assert.IsNull(Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(null)), Now)?.CreatedAt, "Zero: data non scritta."); + Assert.IsNull(Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(new DateTimeOffset(1904, 1, 2, 0, 0, 0, TimeSpan.Zero))), Now)?.CreatedAt, "Una data del 1904 non è plausibile."); + Assert.IsNull(Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(Now.AddDays(10))), Now)?.CreatedAt, "Una data nel futuro non è plausibile."); + Assert.IsNull(Mp4Reader.Read(new MemoryStream("not a movie at all"u8.ToArray()), Now)); + } + + [TestMethod] + public void AnMp4MadeByFfmpegCarriesItsCreationTime() + { + using var temp = new TempFolder("mp4"); + var path = temp.Combine("prova.mp4"); + var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero); + if (!ImportTestFiles.TryMakeMp4WithFfmpeg(path, created)) + { + Assert.Inconclusive("ffmpeg non è installato: la prova sulle intestazioni sintetiche copre il lettore."); + } + + Assert.AreEqual("video/mp4", MediaSniffer.DetectFile(path)?.ContentType); + var info = Mp4Reader.ReadFile(path, Now); + Assert.AreEqual(created, info?.CreatedAt); + Assert.AreEqual(64, info?.Width); + Assert.AreEqual(48, info?.Height); + Assert.IsTrue(info?.Duration > TimeSpan.FromMilliseconds(500)); + } + + [TestMethod] + public async Task FfprobeIsAnOptionalExtra() + { + var parsed = FfprobeVideoMetadataProbe.Parse(""" + {"streams":[{"codec_type":"audio"},{"codec_type":"video","width":1920,"height":1080,"tags":{"rotate":"90"}}], + "format":{"duration":"12.500000","tags":{"creation_time":"2020-08-09T10:11:12.000000Z"}}} + """); + Assert.AreEqual(new DateTimeOffset(2020, 8, 9, 10, 11, 12, TimeSpan.Zero), parsed?.CreatedAt); + Assert.AreEqual(TimeSpan.FromSeconds(12.5), parsed?.Duration); + Assert.AreEqual((1080, 1920), (parsed?.Width, parsed?.Height)); + Assert.IsNull(FfprobeVideoMetadataProbe.Parse("non json")); + Assert.AreEqual(640, FfprobeVideoMetadataProbe.Parse("""{"streams":[{"codec_type":"video","width":640,"height":480,"tags":{"rotate":0}}],"format":{"tags":{"creation_time":5}}}""")?.Width, "Valori di tipo inatteso non fanno fallire la lettura."); + + var probe = FfprobeVideoMetadataProbe.TryCreate(); + if (probe is null) + { + Assert.Inconclusive("ffprobe non è installato."); + return; + } + + using var temp = new TempFolder("ffprobe"); + var path = temp.Combine("prova.mp4"); + var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero); + if (!ImportTestFiles.TryMakeMp4WithFfmpeg(path, created)) + { + Assert.Inconclusive("ffmpeg non è installato."); + } + + var metadata = await probe.ProbeAsync(path); + Assert.AreEqual(created, metadata?.CreatedAt); + Assert.AreEqual(64, metadata?.Width); + } + + [TestMethod] + public void DatesAreFoundInCommonFileNames() + { + var zone = TestZones.Rome; + static DateTimeOffset Rome(int y, int mo, int d, int h, int mi, int s) => new DateTimeOffset(y, mo, d, h, mi, s, TimeSpan.Zero).AddHours(mo is >= 4 and <= 10 ? -2 : -1); + + Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("IMG_20210506_070809", zone, Now)?.Instant); + Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("VID_20210506_070809", zone, Now)?.Instant); + Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("PXL_20210506_070809123", zone, Now)?.Instant); + Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("2021-05-06 07.08.09", zone, Now)?.Instant); + Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("WhatsApp Image 2021-05-06 at 07.08.09", zone, Now)?.Instant); + Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("Screenshot_2021-05-06-07-08-09", zone, Now)?.Instant); + Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 7, 8, 9, TimeSpan.Zero), FileNameDates.Find("2021-05-06_07-08-09_UTC", zone, Now)?.Instant, "«_UTC» dice che l'ora è universale."); + + var dayOnly = FileNameDates.Find("IMG-20210506-WA0001", zone, Now); + Assert.IsTrue(dayOnly?.DayOnly); + Assert.AreEqual(Rome(2021, 5, 6, 12, 0, 0), dayOnly?.Instant); + + Assert.IsNull(FileNameDates.Find("2567890123456789012_123456", zone, Now), "Le cifre di un identificativo non sono una data."); + Assert.IsNull(FileNameDates.Find("IMG_20211306_070809", zone, Now), "Mese 13: non è una data."); + Assert.IsNull(FileNameDates.Find("IMG_20300506_070809", zone, Now), "Una data nel futuro non è plausibile."); + Assert.IsNull(FileNameDates.Find("vacanze al mare", zone, Now)); + } + + private static byte[] Ftyp(string major, params string[] compatible) + { + var body = Encoding.ASCII.GetBytes(major).Concat(new byte[] { 0, 0, 0, 0 }).Concat(compatible.SelectMany(Encoding.ASCII.GetBytes)).ToArray(); + var box = new byte[8 + body.Length + 16]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(box, (uint)(8 + body.Length)); + "ftyp"u8.CopyTo(box.AsSpan(4)); + body.CopyTo(box.AsSpan(8)); + return box; + } +} diff --git a/tests/Febe.Tests/Import/RecognizerTests.cs b/tests/Febe.Tests/Import/RecognizerTests.cs new file mode 100644 index 0000000..cc2352f --- /dev/null +++ b/tests/Febe.Tests/Import/RecognizerTests.cs @@ -0,0 +1,166 @@ +using Febe.Core.Domain; +using Febe.Core.Import; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Import; + +[TestClass] +public sealed class RecognizerTests +{ + private static readonly DateTimeOffset Now = new(2026, 10, 13, 8, 0, 0, TimeSpan.Zero); + + private static ImportRecognizers Recognizers(bool stogram = false) => ImportRecognizers.Create(TestZones.Rome, () => Now, stogram); + + [TestMethod] + public void AFolderOfAccountsAndAFolderThatIsOneAccountAreTold() + { + using var temp = new TempFolder("layout"); + var many = temp.Combine("archivio"); + Directory.CreateDirectory(Path.Combine(many, "marta.demo", "storie")); + Directory.CreateDirectory(Path.Combine(many, "Foto sparse")); + var layout = SourceLayout.Inspect(many); + Assert.IsFalse(layout.RootIsAccount); + Assert.AreEqual(("marta.demo", "storie/2021/a.jpg"), layout.Split("marta.demo/storie/2021/a.jpg")); + Assert.AreEqual((string.Empty, "sciolto.jpg"), layout.Split("sciolto.jpg")); + Assert.IsNull(layout.AccountFolderName(string.Empty), "I file sciolti in cima non hanno un account probabile."); + + var one = temp.Combine("luca.viaggi.demo"); + Directory.CreateDirectory(Path.Combine(one, "post", "2024")); + Directory.CreateDirectory(Path.Combine(one, "Stories")); + Directory.CreateDirectory(Path.Combine(one, "In evidenza")); + var single = SourceLayout.Inspect(one); + Assert.IsTrue(single.RootIsAccount, "Solo cartelle di tipo: la cartella scelta è un account."); + Assert.AreEqual((string.Empty, "post/2024/a.jpg"), single.Split("post/2024/a.jpg")); + Assert.AreEqual("luca.viaggi.demo", single.AccountFolderName(string.Empty)); + + Assert.AreEqual("marta.demo", SourceLayout.UsernameFrom("Marta.Demo")); + Assert.AreEqual("marta.demo", SourceLayout.UsernameFrom("@marta.demo")); + Assert.IsNull(SourceLayout.UsernameFrom("Foto sparse"), "Uno spazio non sta in un nome utente."); + Assert.IsNull(SourceLayout.UsernameFrom("2019"), "Un anno non è un account."); + Assert.IsNull(SourceLayout.UsernameFrom("storie")); + Assert.IsNull(SourceLayout.UsernameFrom(".nascosta")); + Assert.IsNull(SourceLayout.UsernameFrom("un.nome.decisamente.troppo.lungo.per.instagram")); + } + + [TestMethod] + public void TheGenericRecognizerReadsAccountKindAndDate() + { + var layout = SourceLayout.Create("/importa/archivio", rootIsAccount: false, ["marta.demo"]); + var recognizers = Recognizers(); + + var story = recognizers.Recognize(new ImportFileContext(layout, "marta.demo/Storie/IMG_20210506_070809.jpg")); + Assert.AreEqual("marta.demo", story.AccountUsername); + Assert.AreEqual(EntryKind.Story, story.Kind); + Assert.AreEqual(ImportDateSource.FileName, story.DateSource); + Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 5, 8, 9, TimeSpan.Zero), story.Date); + Assert.IsNull(story.InstagramId, "Il riconoscitore generico non indovina identificativi."); + + var highlight = recognizers.Recognize(new ImportFileContext(layout, "marta.demo/highlights/Estate 2025/foto.jpg")); + Assert.AreEqual(EntryKind.Highlight, highlight.Kind); + Assert.AreEqual("Estate 2025", highlight.HighlightTitle); + + var tagged = recognizers.Recognize(new ImportFileContext(layout, "marta.demo/tagged/foto (2).jpg")); + Assert.AreEqual(EntryKind.Tagged, tagged.Kind); + Assert.IsNull(tagged.Date); + } + + [TestMethod] + public void FebeNamesGiveDateCodeAndPosition() + { + var layout = SourceLayout.Create("/importa/marta.demo", rootIsAccount: true); + var recognizers = Recognizers(); + + var post = recognizers.Recognize(new ImportFileContext(layout, "post/2026/2026-10-10_18-22-05_DBx3kQ2_2.jpg")); + Assert.AreEqual("febe", post.Recognizer); + Assert.AreEqual("DBx3kQ2", post.Code); + Assert.IsNull(post.InstagramId); + Assert.AreEqual(2, post.Position); + Assert.AreEqual(EntryKind.Post, post.Kind); + Assert.AreEqual(new DateTimeOffset(2026, 10, 10, 16, 22, 5, TimeSpan.Zero), post.Date, "Le ore nei nomi sono quelle di Alberto."); + Assert.AreEqual("marta.demo", post.AccountUsername); + + var story = recognizers.Recognize(new ImportFileContext(layout, "storie/2026/2026-10-13_09-41-07_3742118_1.mp4")); + Assert.AreEqual("3742118", story.InstagramId, "Per storie ed evidenza il codice è l'identificativo."); + Assert.AreEqual(EntryKind.Story, story.Kind); + + var highlight = recognizers.Recognize(new ImportFileContext(layout, "evidenza/Estate 2025/2025-08-02_10-11-12_3391207_1 (2).jpg")); + Assert.AreEqual(EntryKind.Highlight, highlight.Kind); + Assert.AreEqual("Estate 2025", highlight.HighlightTitle); + Assert.AreEqual("3391207", highlight.InstagramId); + + var instaloader = recognizers.Recognize(new ImportFileContext(layout, "2021-05-06_07-08-09_UTC_1.jpg")); + Assert.IsNull(instaloader.Code, "«UTC» non è un codice."); + Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 7, 8, 9, TimeSpan.Zero), instaloader.Date); + } + + [TestMethod] + public async Task FebeJournalGivesIdentifiersCaptionsAndExactTimes() + { + using var temp = new TempFolder("febe-sorgente"); + var account = temp.Combine("marta.demo"); + Directory.CreateDirectory(Path.Combine(account, "post", "2025")); + await AccountJournal.AppendAsync(account, new JournalLine + { + Op = JournalOps.Save, + At = Now, + Account = new JournalAccount("4242", "marta.demo"), + Entry = new JournalEntry { Kind = "post", Id = "3100000000000000001", Code = "CxYz123", PublishedAt = new DateTimeOffset(2025, 3, 1, 9, 30, 15, 250, TimeSpan.Zero), Caption = "Una didascalia" }, + Files = + [ + new JournalFile { N = 1, Type = "photo", Path = "post/2025/scelto-da-me.jpg", Id = "3100000000000000002" }, + new JournalFile { N = 2, Type = "photo", Path = "post/2025/altro.jpg" }, + ], + }); + + var layout = SourceLayout.Create(temp.Path, rootIsAccount: false, ["marta.demo"]); + var recognizers = Recognizers(); + await recognizers.PrepareAsync(layout, CancellationToken.None); + var hints = recognizers.Recognize(new ImportFileContext(layout, "marta.demo/post/2025/scelto-da-me.jpg")); + Assert.AreEqual(ImportDateSource.Journal, hints.DateSource); + Assert.AreEqual(new DateTimeOffset(2025, 3, 1, 9, 30, 15, 250, TimeSpan.Zero), hints.Date); + Assert.AreEqual("3100000000000000001", hints.InstagramId); + Assert.AreEqual("3100000000000000002", hints.MediaInstagramId); + Assert.AreEqual("CxYz123", hints.Code); + Assert.AreEqual(1, hints.Position); + Assert.AreEqual("Una didascalia", hints.Caption); + Assert.AreEqual("4242", hints.AccountInstagramId); + Assert.IsFalse(hints.ToString().Contains("didascalia", StringComparison.Ordinal), "La didascalia non finisce mai in ToString."); + + Assert.AreEqual(2, recognizers.Recognize(new ImportFileContext(layout, "marta.demo/post/2025/altro.jpg")).Position); + } + + [TestMethod] + public void TheStogramHypothesisReadsSyntheticNamesOnlyWhenAskedFor() + { + var layout = SourceLayout.Create("/importa/4K Stogram", rootIsAccount: false, ["vecchio.profilo.demo"]); + const string name = "vecchio.profilo.demo/stories/2019-06-01 21.15.30 2071234567890123456_1234567890.jpg"; + + var off = Recognizers().Recognize(new ImportFileContext(layout, name)); + Assert.IsNull(off.InstagramId, "Spenta per impostazione predefinita: nessun identificativo dall'ipotesi."); + Assert.IsFalse(off.Hypothesis); + Assert.AreEqual(new DateTimeOffset(2019, 6, 1, 19, 15, 30, TimeSpan.Zero), off.Date, "La data la legge comunque il riconoscitore generico."); + + var on = Recognizers(stogram: true).Recognize(new ImportFileContext(layout, name)); + Assert.IsTrue(on.Hypothesis); + Assert.AreEqual("4k-stogram-ipotesi", on.Recognizer); + Assert.AreEqual("2071234567890123456", on.InstagramId); + Assert.AreEqual("1234567890", on.AccountInstagramId); + Assert.AreEqual(EntryKind.Story, on.Kind); + Assert.AreEqual("vecchio.profilo.demo", on.AccountUsername); + + var copy = Recognizers(stogram: true).Recognize(new ImportFileContext(layout, "vecchio.profilo.demo/2019-06-01 21.15.30 2071234567890123456_1234567890 (2).jpg")); + Assert.AreEqual("2071234567890123456", copy.InstagramId); + Assert.IsNull(Recognizers(stogram: true).Recognize(new ImportFileContext(layout, "vecchio.profilo.demo/IMG_0001.jpg")).InstagramId); + } + + [TestMethod] + public void A4KStogramFolderIsRecognizedWithoutOpeningItsDatabase() + { + using var temp = new TempFolder("stogram"); + Assert.IsFalse(StogramHypothesisRecognizer.LooksLikeStogramFolder(temp.Path)); + File.WriteAllText(temp.Combine("stogram.sqlite"), "non è un database: Febe non lo apre"); + Assert.IsTrue(StogramHypothesisRecognizer.LooksLikeStogramFolder(temp.Path)); + Assert.IsTrue(ImportSources.IsIgnoredFile("stogram.sqlite"), "I database di 4K Stogram non si importano né si leggono."); + } +} diff --git a/tests/Febe.Tests/Import/Support/ImportTestBed.cs b/tests/Febe.Tests/Import/Support/ImportTestBed.cs new file mode 100644 index 0000000..ea19dc0 --- /dev/null +++ b/tests/Febe.Tests/Import/Support/ImportTestBed.cs @@ -0,0 +1,224 @@ +using System.Security.Cryptography; +using Febe.Core.Domain; +using Febe.Core.Import; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Import.Support; + +/// Read-only detection decided by the test. +internal sealed class FixedAccessProbe(bool readOnly) : ISourceAccessProbe +{ + public bool IsReadOnly(string fullPath) => readOnly; +} + +/// +/// The real file system, except that copies in the library can be damaged right before «Sposta» verifies them, and +/// deletions of originals are counted. +/// +internal sealed class CorruptingFileSystem(string libraryRoot) : IImportFileSystem +{ + private readonly string _libraryRoot = Path.GetFullPath(libraryRoot); + private readonly HashSet _damaged = new(StringComparer.Ordinal); + + /// Damage every library file (once: the damage stays) before it is hashed. + public bool CorruptCopies { get; set; } + + public List Deleted { get; } = []; + + public Stream OpenRead(string fullPath) => ImportFileSystem.Instance.OpenRead(fullPath); + + public Task ComputeSha256Async(string fullPath, CancellationToken ct) + { + var full = Path.GetFullPath(fullPath); + if (CorruptCopies && full.StartsWith(_libraryRoot, StringComparison.Ordinal) && _damaged.Add(full)) + { + var bytes = File.ReadAllBytes(full); + bytes[^1] ^= 0xFF; + File.WriteAllBytes(full, bytes); + } + + return ImportFileSystem.Instance.ComputeSha256Async(fullPath, ct); + } + + /// Deleting an original fails, as for a file open in another program. + public bool FailDeletes { get; set; } + + public void DeleteOriginal(string fullPath) + { + if (FailDeletes) + { + throw new IOException("File in uso."); + } + + Deleted.Add(fullPath); + ImportFileSystem.Instance.DeleteOriginal(fullPath); + } +} + +/// A library with database and services plus a source folder to import from. +internal sealed class ImportTestBed : IAsyncDisposable +{ + private ImportTestBed(TestLibrary library, TempFolder temp, bool readOnlySource) + { + Library = library; + Temp = temp; + Source = temp.Combine("sorgente"); + Directory.CreateDirectory(Source); + FileSystem = new CorruptingFileSystem(library.Layout.Root); + Environment = new ImportEnvironment + { + Storage = library.Db, + Layout = library.Layout, + Journal = library.Journal, + Clock = library.Clock, + Thumbnails = library.Thumbnails, + HashIndex = library.Index, + DataFolder = library.Data.Root, + AccessProbe = new FixedAccessProbe(readOnlySource), + FileSystem = FileSystem, + Parallelism = 2, + }; + } + + public TestLibrary Library { get; } + + public TempFolder Temp { get; } + + /// Full path of the source folder. + public string Source { get; } + + public CorruptingFileSystem FileSystem { get; } + + public ImportEnvironment Environment { get; private set; } + + public ImportAnalyzer Analyzer => new(Environment); + + public ImportCopier Copier => new(Environment); + + public ImportReview Review => new(Environment); + + public ImportReports Reports => new(Environment); + + public static async Task CreateAsync(TempFolder temp, bool readOnlySource = false) => + new(await TestLibrary.CreateAsync(temp), temp, readOnlySource); + + /// Uses another environment (e.g. with the Docker root). + public void Use(ImportEnvironment environment) => Environment = environment; + + /// Writes a file in the source; the modification time is set when given. + public string Write(string relativePath, byte[] bytes, DateTime? modifiedUtc = null) + { + var full = Path.Combine(Source, relativePath.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(full)!); + File.WriteAllBytes(full, bytes); + File.SetLastWriteTimeUtc(full, modifiedUtc ?? new DateTime(2020, 1, 2, 3, 4, 5, DateTimeKind.Utc)); + return full; + } + + /// Path, size, modification time and SHA-256 of every file of the source: compares «before» and «after». + public IReadOnlyList Fingerprint() => + Directory.EnumerateFiles(Source, "*", SearchOption.AllDirectories) + .Order(StringComparer.Ordinal) + .Select(f => + { + var info = new FileInfo(f); + return $"{Path.GetRelativePath(Source, f)}|{info.Length}|{info.LastWriteTimeUtc:O}|{Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(f)))}"; + }) + .ToList(); + + /// Checks the source, records the import and runs the analysis to the end. + public async Task AnalyzeAsync(ImportAnalysisOptions? options = null) + { + var info = Environment.CreateSources().Inspect(Source); + var run = await Analyzer.CreateRunAsync(info, options); + return await Analyzer.AnalyzeAsync(run.Id); + } + + public async Task> FilesAsync(long runId) => + await Library.Db.Imports.ListFilesAsync(new Core.Storage.ImportFileQuery { RunId = runId, Limit = 10_000 }); + + public async Task FileAsync(long runId, string relativePath) => + await Library.Db.Imports.FindFileAsync(runId, relativePath) ?? throw new AssertFailedException($"{relativePath} non è nell'importazione."); + + /// An account with a photo already in the library (stored as the collection would). + public async Task<(Account Account, EntryWithMedia Saved)> AccountWithPhotoAsync(string username, string instagramId, byte[] photo, string? code = null, DateTimeOffset? publishedAt = null) + { + var account = await Library.Db.Accounts.FindByUsernameAsync(username) ?? await Library.Db.Accounts.AddAsync(Make.Account(username)); + var entry = Make.Entry(account.Id, instagramId, publishedAt ?? Make.T0.AddDays(-30)) with { Code = code ?? "C" + instagramId }; + var saved = await Library.SaveAsync(account, entry, [new TestFile(Make.Photo(1), photo, ".jpg")]); + return (account, saved); + } + + public ValueTask DisposeAsync() => Library.DisposeAsync(); +} + +/// +/// Reading a source file whose path matches waits until the job is cancelled: an import can +/// be interrupted at a known point. +/// +internal sealed class GatedFileSystem(IImportFileSystem inner, Func blocks) : IImportFileSystem +{ + /// Set when the first blocked file is opened. + public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Stream OpenRead(string fullPath) + { + var stream = inner.OpenRead(fullPath); + if (!blocks(fullPath)) + { + return stream; + } + + Reached.TrySetResult(); + return new BlockedStream(stream); + } + + public Task ComputeSha256Async(string fullPath, CancellationToken ct) => inner.ComputeSha256Async(fullPath, ct); + + public void DeleteOriginal(string fullPath) => inner.DeleteOriginal(fullPath); + + private sealed class BlockedStream(Stream inner) : Stream + { + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => inner.Length; + + public override long Position { get => inner.Position; set => throw new NotSupportedException(); } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + await Task.Delay(Timeout.Infinite, cancellationToken); + return 0; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + inner.Dispose(); + } + + base.Dispose(disposing); + } + } +} diff --git a/tests/Febe.Tests/Import/Support/ImportTestFiles.cs b/tests/Febe.Tests/Import/Support/ImportTestFiles.cs new file mode 100644 index 0000000..d6ad1de --- /dev/null +++ b/tests/Febe.Tests/Import/Support/ImportTestFiles.cs @@ -0,0 +1,259 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using System.Text; +using Febe.Tests.Support; +using SkiaSharp; + +namespace Febe.Tests.Import.Support; + +/// Bytes of test media written by hand: JPEGs with an EXIF date, PNGs with eXIf, MP4/MOV headers. +internal static class ImportTestFiles +{ + private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero); + + /// A generated photo as JPEG. + public static byte[] Photo(int scene, int width = 800, int height = 600, int quality = 88) + { + using var bitmap = TestImages.Scene(scene, width, height); + return TestImages.Jpeg(bitmap, quality); + } + + /// + /// A TIFF structure (big or little endian) with IFD0 → Exif IFD holding DateTimeOriginal and/or CreateDate and an + /// optional OffsetTimeOriginal: the content of an EXIF block after «Exif\0\0». + /// + public static byte[] Tiff(string? dateTimeOriginal, string? createDate = null, string? offsetOriginal = null, bool littleEndian = false) + { + var tags = new List<(ushort Tag, string Value)>(); + if (dateTimeOriginal is not null) + { + tags.Add((0x9003, dateTimeOriginal)); + } + + if (createDate is not null) + { + tags.Add((0x9004, createDate)); + } + + if (offsetOriginal is not null) + { + tags.Add((0x9011, offsetOriginal)); + } + + tags.Sort((a, b) => a.Tag.CompareTo(b.Tag)); + var buffer = new byte[1024]; + var span = buffer.AsSpan(); + void U16(int at, ushort v) + { + if (littleEndian) + { + BinaryPrimitives.WriteUInt16LittleEndian(buffer.AsSpan(at), v); + } + else + { + BinaryPrimitives.WriteUInt16BigEndian(buffer.AsSpan(at), v); + } + } + + void U32(int at, uint v) + { + if (littleEndian) + { + BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(at), v); + } + else + { + BinaryPrimitives.WriteUInt32BigEndian(buffer.AsSpan(at), v); + } + } + + (littleEndian ? "II"u8 : "MM"u8).CopyTo(span); + U16(2, 42); + U32(4, 8); + + // IFD0 at 8: one entry, the Exif IFD pointer. + U16(8, 1); + U16(10, 0x8769); + U16(12, 4); // LONG + U32(14, 1); + const int exifIfd = 26; + U32(18, exifIfd); + U32(22, 0); // no next IFD + + // Exif IFD at 26: the ASCII tags, values after the IFD. + U16(exifIfd, (ushort)tags.Count); + var valueAt = exifIfd + 2 + (tags.Count * 12) + 4; + for (var i = 0; i < tags.Count; i++) + { + var at = exifIfd + 2 + (i * 12); + var bytes = Encoding.ASCII.GetBytes(tags[i].Value + "\0"); + U16(at, tags[i].Tag); + U16(at + 2, 2); // ASCII + U32(at + 4, (uint)bytes.Length); + if (bytes.Length <= 4) + { + bytes.CopyTo(span[(at + 8)..]); + } + else + { + U32(at + 8, (uint)valueAt); + bytes.CopyTo(span[valueAt..]); + valueAt += bytes.Length; + } + } + + U32(exifIfd + 2 + (tags.Count * 12), 0); + return buffer[..valueAt]; + } + + /// Inserts an APP1 «Exif» segment with the given TIFF block right after the SOI marker of a JPEG. + public static byte[] JpegWithExif(byte[] jpeg, byte[] tiff) + { + var length = 2 + 6 + tiff.Length; + var app1 = new byte[2 + length]; + app1[0] = 0xFF; + app1[1] = 0xE1; + BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(2), (ushort)length); + "Exif\0\0"u8.CopyTo(app1.AsSpan(4)); + tiff.CopyTo(app1.AsSpan(10)); + return [.. jpeg.AsSpan(0, 2), .. app1, .. jpeg.AsSpan(2)]; + } + + /// A generated JPEG photo with DateTimeOriginal «yyyy:MM:dd HH:mm:ss» written by hand. + public static byte[] PhotoWithExifDate(int scene, DateTime local, string? offset = null, int width = 800, int height = 600) => + JpegWithExif(Photo(scene, width, height), Tiff(local.ToString("yyyy:MM:dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture), offsetOriginal: offset)); + + /// A PNG with an eXIf chunk inserted before the image data. + public static byte[] PngWithExif(byte[] png, byte[] tiff) + { + // After the signature (8) comes IHDR (8 + 13 + 4 = 25 bytes). + var chunk = new byte[12 + tiff.Length]; + BinaryPrimitives.WriteUInt32BigEndian(chunk, (uint)tiff.Length); + "eXIf"u8.CopyTo(chunk.AsSpan(4)); + tiff.CopyTo(chunk.AsSpan(8)); + // CRC left at zero: readers of dates do not check it. + return [.. png.AsSpan(0, 33), .. chunk, .. png.AsSpan(33)]; + } + + /// + /// A minimal ISO media file: ftyp, then (or after the media data) a moov with mvhd and a video tkhd. The payload + /// makes each file different. + /// + public static byte[] Mp4( + DateTimeOffset? createdAt, + int width = 1080, + int height = 1920, + int durationMs = 15_000, + int payloadSeed = 1, + string brand = "isom", + bool moovAtEnd = false, + bool rotated = false, + bool withFtyp = true) + { + using var output = new MemoryStream(); + if (withFtyp) + { + WriteBox(output, "ftyp", [.. Encoding.ASCII.GetBytes(brand), 0, 0, 2, 0, .. Encoding.ASCII.GetBytes("isommp41")]); + } + + var payload = new byte[4096]; + new Random(payloadSeed).NextBytes(payload); + var mvhd = new byte[100]; + var creation = createdAt is { } c ? (uint)(c - Epoch1904).TotalSeconds : 0u; + BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(4), creation); + BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(8), creation); + BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(12), 1000); + BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(16), (uint)durationMs); + + var tkhd = new byte[84]; + tkhd[3] = 3; // enabled, in movie + BinaryPrimitives.WriteUInt32BigEndian(tkhd.AsSpan(4), creation); + BinaryPrimitives.WriteUInt32BigEndian(tkhd.AsSpan(12), 1); + var matrix = tkhd.AsSpan(40, 36); + int[] values = rotated ? [0, 0x10000, 0, -0x10000, 0, 0, 0, 0, 0x40000000] : [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000]; + for (var i = 0; i < 9; i++) + { + BinaryPrimitives.WriteInt32BigEndian(matrix[(i * 4)..], values[i]); + } + + BinaryPrimitives.WriteUInt32BigEndian(tkhd.AsSpan(76), (uint)width << 16); + BinaryPrimitives.WriteUInt32BigEndian(tkhd.AsSpan(80), (uint)height << 16); + + using var trak = new MemoryStream(); + WriteBox(trak, "tkhd", tkhd); + using var moov = new MemoryStream(); + WriteBox(moov, "mvhd", mvhd); + WriteBox(moov, "trak", trak.ToArray()); + + if (moovAtEnd) + { + WriteBox(output, "mdat", payload); + WriteBox(output, "moov", moov.ToArray()); + } + else + { + WriteBox(output, "moov", moov.ToArray()); + WriteBox(output, "mdat", payload); + } + + return output.ToArray(); + } + + /// Makes a real one-second MP4 with ffmpeg and the given creation time; false when ffmpeg is missing. + public static bool TryMakeMp4WithFfmpeg(string path, DateTimeOffset createdAt) + { + var ffmpeg = new[] { "/usr/bin/ffmpeg", "/usr/local/bin/ffmpeg" }.FirstOrDefault(File.Exists); + if (ffmpeg is null) + { + return false; + } + + var start = new ProcessStartInfo(ffmpeg) { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false }; + foreach (var argument in new[] + { + "-hide_banner", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x3366aa:s=64x48:d=1:r=10", + "-metadata", "creation_time=" + createdAt.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss", System.Globalization.CultureInfo.InvariantCulture) + "Z", + "-c:v", "mpeg4", "-f", "mp4", path, + }) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start)!; + process.StandardError.ReadToEnd(); + process.WaitForExit(30_000); + return process.ExitCode == 0 && File.Exists(path); + } + + /// The PNG encoding of a generated scene. + public static byte[] Png(int scene, int width = 400, int height = 300) + { + using var bitmap = TestImages.Scene(scene, width, height); + return TestImages.Png(bitmap); + } + + /// A resized and recompressed copy of a scene (a probable duplicate). + public static byte[] Resized(int scene, int width, int height, int targetWidth, int targetHeight, int quality = 60) + { + using var bitmap = TestImages.Scene(scene, width, height); + using var smaller = TestImages.Resize(bitmap, targetWidth, targetHeight); + return TestImages.Jpeg(smaller, quality); + } + + /// A crop of a scene: the top-left quarter (not a duplicate). + public static byte[] Cropped(int scene, int width, int height) + { + using var bitmap = TestImages.Scene(scene, width, height); + using var crop = TestImages.Crop(bitmap, new SKRectI(0, 0, width / 2, height / 2)); + return TestImages.Jpeg(crop, 88); + } + + private static void WriteBox(Stream output, string type, byte[] body) + { + Span header = stackalloc byte[8]; + BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(body.Length + 8)); + Encoding.ASCII.GetBytes(type).CopyTo(header[4..]); + output.Write(header); + output.Write(body); + } +}