M7 Importazione: sorgenti con sola lettura riconosciuta, analisi in sola lettura interrompibile e ripristinabile (tipo dal contenuto, SHA-256, impronta, date da nome, EXIF scritto a mano, mvhd e ffprobe facoltativo), riconoscitori Febe, generico e 4K Stogram come ipotesi spenta, confronto con la libreria e dentro la sorgente, associazione cartelle-account, decisioni sui doppioni, copia o spostamento verificati con sostituzione sicura, resoconto e CSV; prove

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 18:32:01 +00:00
1 parent 6ff11ac8e3
commit 5e77bdefe0
32 files changed
+7707 -3

No files matched your search

+14
View File
@@ -47,6 +47,13 @@ public enum ImportOutcome
/// <summary>«Non riconosciuto»: neither a photo nor a video. Ignored and listed.</summary>
Unrecognized,
/// <summary>
/// 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.
/// </summary>
IdenticalInSource,
}
/// <summary>Alberto's decision for a file of an import.</summary>
@@ -83,6 +90,9 @@ public enum ImportDateSource
FileName,
Metadata,
ModifiedTime,
/// <summary>The <c>_febe.jsonl</c> of a Febe library used as source: the exact publication time.</summary>
Journal,
}
/// <summary>An import (spec §8.3 <c>import_run</c>).</summary>
@@ -177,5 +187,9 @@ public sealed record ImportFile
/// <summary>Path of the copy relative to the account folder.</summary>
public string? DestinationPath { get; init; }
/// <summary>
/// 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).
/// </summary>
public string? LastError { get; init; }
}
+140
View File
@@ -0,0 +1,140 @@
using System.Security.Cryptography;
using Febe.Core.Domain;
using Febe.Core.Library;
namespace Febe.Core.Import;
/// <summary>What the content of one file says, measured without changing anything.</summary>
internal sealed record ContentFacts(
DetectedType? Type,
long Bytes,
string? Sha256,
int? Width,
int? Height,
TimeSpan? Duration,
ulong? PerceptualHash,
DateTimeOffset? MetadataDate,
string? Error);
/// <summary>
/// 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, <c>mvhd</c> for MP4/MOV, ffprobe as an extra for the rest).
/// </summary>
internal static class ContentAnalysis
{
/// <summary>Photos up to this size are read once into memory (hash, EXIF and decoding from the same bytes).</summary>
private const long InMemoryLimit = 64L * 1024 * 1024;
public static async Task<ContentFacts> 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<ContentFacts> 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<Stream> 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<ContentFacts> 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);
}
}
+321
View File
@@ -0,0 +1,321 @@
using System.Buffers.Binary;
using System.Globalization;
using Febe.Core.Domain;
namespace Febe.Core.Import;
/// <summary>
/// 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: <c>DateTimeOriginal</c> (0x9003), then <c>CreateDate</c>
/// (0x9004, «DateTimeDigitized»), with <c>OffsetTimeOriginal</c>/<c>OffsetTimeDigitized</c>/<c>OffsetTime</c> when the
/// camera wrote the zone. The modification date of IFD0 (0x0132) is not used: editors rewrite it.
/// <para>
/// Containers: JPEG (APP1 «Exif»), TIFF and raw formats built on it, PNG (<c>eXIf</c> chunk), WebP (<c>EXIF</c> chunk).
/// HEIC keeps its EXIF in an item of the <c>meta</c> box and is not read. Every offset is checked: a damaged block gives
/// no date, never an exception.
/// </para>
/// </summary>
public static class ExifDateReader
{
/// <summary>Bytes to read from the start of a file: EXIF blocks sit near the start.</summary>
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;
/// <summary>
/// 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 <paramref name="zone"/> (Alberto's: cameras write local time).
/// </summary>
public static DateTimeOffset? Read(ReadOnlySpan<byte> 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
}
}
/// <summary>The TIFF structure holding the EXIF data of a JPEG, TIFF, PNG or WebP; empty when there is none.</summary>
internal static ReadOnlySpan<byte> FindTiff(ReadOnlySpan<byte> 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<byte> FindInJpeg(ReadOnlySpan<byte> 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<byte> FindInPng(ReadOnlySpan<byte> 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<byte> FindInWebp(ReadOnlySpan<byte> 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<byte> 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);
}
/// <summary>«2021:05:06 07:08:09» with an optional «+02:00» zone.</summary>
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);
}
/// <summary>«+02:00» or «-05:00».</summary>
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<byte> 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<byte> 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<byte> data, int offset, bool little) => little
? BinaryPrimitives.ReadUInt16LittleEndian(data.Slice(offset, 2))
: BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset, 2));
private static uint U32(ReadOnlySpan<byte> data, int offset, bool little) => little
? BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset, 4))
: BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset, 4));
}
+98
View File
@@ -0,0 +1,98 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Febe.Core.Domain;
namespace Febe.Core.Import;
/// <summary>A date found in a file name.</summary>
/// <param name="Instant">The instant (UTC offset applied).</param>
/// <param name="DayOnly">Only the day was in the name: the time is noon, local.</param>
public readonly record struct NameDate(DateTimeOffset Instant, bool DayOnly);
/// <summary>
/// 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.
/// <list type="bullet">
/// <item><c>2021-05-06 07.08.09</c>, <c>2021-05-06_07-08-09</c>, <c>WhatsApp Image 2021-05-06 at 07.08.09</c>;</item>
/// <item><c>IMG_20210506_070809</c>, <c>VID_20210506_070809</c>, <c>PXL_20210506_070809123</c>, <c>20210506_070809</c>;</item>
/// <item>only the day: <c>IMG-20210506-WA0001</c>, <c>2021-05-06</c>.</item>
/// </list>
/// </summary>
public static partial class FileNameDates
{
/// <summary>The first plausible date in a file name without extension; null when there is none.</summary>
/// <param name="stem">The name without extension.</param>
/// <param name="zone">Alberto's zone, for local times.</param>
/// <param name="now">Current time: dates after it (by more than a day) are not plausible.</param>
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(@"(?<!\d)(?<y>(?:19|20)\d{2})-(?<mo>\d{2})-(?<d>\d{2})[ _T-]+(?:at[ _]+)?(?<h>\d{2})[.\-:h_](?<mi>\d{2})[.\-:m_](?<s>\d{2})(?!\d)(?<utc>_UTC)?", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)]
private static partial Regex SeparatedDateTime();
[GeneratedRegex(@"(?<!\d)(?<y>(?:19|20)\d{2})(?<mo>\d{2})(?<d>\d{2})[_\-T ]?(?<h>\d{2})(?<mi>\d{2})(?<s>\d{2})(?:\d{1,3})?(?!\d)", RegexOptions.CultureInvariant)]
private static partial Regex CompactDateTime();
[GeneratedRegex(@"(?<!\d)(?<y>(?:19|20)\d{2})-(?<mo>\d{2})-(?<d>\d{2})(?!\d)", RegexOptions.CultureInvariant)]
private static partial Regex SeparatedDate();
[GeneratedRegex(@"(?<!\d)(?<y>(?:19|20)\d{2})(?<mo>\d{2})(?<d>\d{2})(?!\d)", RegexOptions.CultureInvariant)]
private static partial Regex CompactDate();
}
+410
View File
@@ -0,0 +1,410 @@
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Import;
/// <summary>
/// Step 2 of the import (spec §9.2, §9.3): lists the source, reads every file and compares it with the library.
/// <para>
/// Strictly read-only: nothing is copied, moved or written into the source. Interruptible (cancellation) and resumable:
/// the state lives in <c>import_run</c> and <c>import_file</c>, 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).
/// </para>
/// </summary>
public sealed class ImportAnalyzer(ImportEnvironment env)
{
private const int BatchSize = 64;
private const int ListingBatchSize = 500;
/// <summary>Records a new import for a checked source (see <see cref="ImportSources.Inspect"/>).</summary>
public async Task<ImportRun> 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;
}
/// <summary>
/// Runs (or resumes) the analysis of an import to the end. On cancellation the import becomes «analisi interrotta»
/// and <see cref="OperationCanceledException"/> is thrown; on another error it becomes «analisi interrotta» with the
/// error and the exception is thrown.
/// </summary>
/// <returns>The import, now waiting for the review.</returns>
public async Task<ImportRun> AnalyzeAsync(long runId, IProgress<ImportProgress>? 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)}, {ItalianText.Number(summary.ByOutcome[ImportOutcome.New])} 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;
}
}
/// <summary>A progress snapshot built from the database (also used by the service for an idle import).</summary>
public async Task<ImportProgress> 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<long> 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;
}
/// <summary>Lists the source and records the files not known yet, in path order (so «the first met» is stable).</summary>
private async Task ListAsync(ImportRun run, SourceLayout layout, IProgress<ImportProgress>? progress, CancellationToken ct)
{
var known = new HashSet<string>(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<string>();
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 (found.Count % 1000 == 0 && found.Count > 0)
{
progress?.Report(new ImportProgress(run.Id, ImportPhase.Listing, 0, known.Count + found.Count, 0, 0, relative, new Dictionary<ImportOutcome, int>(), 0, env.Clock.Now));
}
}
found.Sort(StringComparer.Ordinal);
for (var i = 0; i < found.Count; i += ListingBatchSize)
{
ct.ThrowIfCancellationRequested();
var batch = new List<ImportFile>();
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);
}
}
/// <summary>Files that could not be read last time go back to «da analizzare».</summary>
private async Task RetryUnreadableAsync(long runId, CancellationToken ct)
{
var failed = await env.Storage.Imports.ListFilesAsync(new ImportFileQuery { RunId = runId, State = ImportFileState.Failed, Outcome = ImportOutcome.Pending, Limit = 10_000 }, ct).ConfigureAwait(false);
if (failed.Count > 0)
{
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<ImportProgress>? 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<string, long?>(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<ImportOutcome, int>(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<ImportFile>(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<ImportOutcome, int>(outcomes), 0, env.Clock.Now));
}
}
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>The account a folder probably goes to: by Instagram identifier, then by user name.</summary>
private async Task<long?> 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;
}
/// <summary>
/// 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.
/// </summary>
private async Task ApplyDefaultTargetsAsync(ImportRun run, SourceLayout layout, ImportRecognizers recognizers, CancellationToken ct)
{
var newAccounts = new Dictionary<string, string>(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.",
};
}
+299
View File
@@ -0,0 +1,299 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Import;
/// <summary>What the comparison decided for one file.</summary>
internal sealed record Comparison(ImportOutcome Outcome, long? MatchedMediaId, DuplicatePair? Pair, string? Note);
/// <summary>
/// The comparison with the library (spec §9.3), for one analysis session. In this order:
/// <list type="number">
/// <item>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;</item>
/// <item>same SHA-256 as an earlier file of the source → identical copy in the source;</item>
/// <item>same Instagram identifier or code with a different file → «Doppione probabile» (destination account first, then
/// the rest of the library);</item>
/// <item>perceptual hash within <see cref="PerceptualHash.DuplicateThreshold"/> of a library photo → «Doppione
/// probabile» (destination account first);</item>
/// <item>the same two checks against earlier files of the source;</item>
/// <item>otherwise «Nuovo».</item>
/// </list>
/// 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.
/// </summary>
internal sealed class ImportComparer
{
private readonly IFebeStorage _storage;
private readonly PerceptualHashIndex _library;
private readonly Func<DateTimeOffset> _now;
private readonly Dictionary<string, List<EntryIdentity>> _entriesById = new(StringComparer.Ordinal);
private readonly Dictionary<string, List<EntryIdentity>> _entriesByCode = new(StringComparer.Ordinal);
private readonly Dictionary<string, List<MediaIdentity>> _mediaById = new(StringComparer.Ordinal);
private readonly Dictionary<long, IReadOnlyList<Media>> _mediaOfEntry = [];
private readonly Dictionary<long, EntryIdentity> _entries = [];
// The source: first file by SHA-256, by identity, and the perceptual hashes of the files that are «Nuovo».
private readonly Dictionary<string, (long Id, string Path)> _sourceSha = new(StringComparer.Ordinal);
private readonly Dictionary<string, long> _sourceIdentity = new(StringComparer.Ordinal);
private readonly PerceptualHashIndex _sourceHashes = new();
private ImportComparer(IFebeStorage storage, PerceptualHashIndex library, Func<DateTimeOffset> now)
{
_storage = storage;
_library = library;
_now = now;
}
/// <summary>Loads the library identifiers and, when resuming, the files of the source already analysed.</summary>
/// <param name="storage">The database.</param>
/// <param name="sharedIndex">The library's perceptual hashes (loaded from the database when null).</param>
/// <param name="runId">The import.</param>
/// <param name="hintsOf">The recognizers' hints of a file already analysed (positions are not stored).</param>
/// <param name="now">Current time.</param>
/// <param name="ct">Cancellation.</param>
public static async Task<ImportComparer> CreateAsync(
IFebeStorage storage,
PerceptualHashIndex? sharedIndex,
long runId,
Func<ImportFile, FileHints> hintsOf,
Func<DateTimeOffset> 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;
}
/// <summary>
/// Compares a file (its <see cref="ImportFile.Id"/> must be set) with the library and with the earlier files of the
/// source, then remembers it for the files that follow.
/// </summary>
public async Task<Comparison> 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<Comparison> 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<Comparison?> 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<string>().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<string> 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);
}
}
/// <summary>Keys that identify the same Instagram file: the item's own id, or the entry id/code with the position.</summary>
private static IEnumerable<string> 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<T>(Dictionary<string, List<T>> map, string key, T value)
{
if (!map.TryGetValue(key, out var list))
{
list = [];
map[key] = list;
}
list.Add(value);
}
}
+759
View File
@@ -0,0 +1,759 @@
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Import;
/// <summary>
/// Step 4 of the import (spec §9.4): copy or move with verification, then the report.
/// <list type="bullet">
/// <item>Files enter the library through <see cref="LibraryIngest"/>, like downloads: safe write with SHA-256, thumbnails,
/// perceptual hashes, <c>_febe.jsonl</c> line, provenance «importato». Nothing is ever overwritten.</item>
/// <item>Files with a known date and code take the name of the library scheme; the others go to
/// <c>importati/</c> with their original name.</item>
/// <item>«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.</item>
/// <item>«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.</item>
/// <item>Resumable: every file has its state; an interrupted copy continues where it stopped (an entry created just before
/// an interruption is reused, not duplicated).</item>
/// </list>
/// </summary>
public sealed class ImportCopier(ImportEnvironment env)
{
private const string ImportedFolder = "importati";
/// <summary>
/// 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 <see cref="OperationCanceledException"/> is thrown.
/// </summary>
public async Task<ImportRun> CopyAsync(long runId, IProgress<ImportProgress>? 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<ImportOutcome, int>(), 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<ImportOutcome, int>(), 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.Files(tally.Copied)} importati";
if (tally.Replaced > 0)
{
text += $" ({ItalianText.Number(tally.Replaced)} al posto di file più piccoli)";
}
if (tally.LeftOut > 0)
{
text += $", {ImportText.Files(tally.LeftOut)} restano fuori";
}
if (tally.Failed > 0)
{
text += $", {ImportText.Files(tally.Failed)} non riusciti";
}
return text + ".";
}
private async Task<Dictionary<long, ImportFile>> LoadFilesAsync(long runId, CancellationToken ct)
{
var files = new Dictionary<long, ImportFile>();
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;
}
/// <summary>Creates the «Solo archivio» accounts chosen in the review and associates their folders.</summary>
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<string, string>(), CancellationToken.None).ConfigureAwait(false);
}
private async Task<ImportFile> 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);
}
}
/// <summary>Copies one file into its destination account as an imported entry (or into an entry it completes).</summary>
private async Task<ImportFile> 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);
}
/// <param name="Entry">The entry that receives the file.</param>
/// <param name="Media">The file record to fill.</param>
/// <param name="ByScheme">The entry has an identity: the file may take the scheme name.</param>
/// <param name="Deleted">The entry was deleted by Alberto «ricordando la scelta»: the file is not imported.</param>
/// <param name="OwnedByThisFile">The entry exists only for this file (created by this import for it).</param>
private sealed record Target(Entry? Entry, Media? Media, bool ByScheme, bool Deleted, bool OwnedByThisFile = false);
/// <summary>
/// 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 <c>importati/</c>.
/// </summary>
private async Task<Target> 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,
};
/// <summary>
/// «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).
/// </summary>
private async Task<ImportFile> 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<string?>(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);
}
/// <summary>Records a stored file; with «Sposta» verifies the copy on disk and only then deletes the original.</summary>
private async Task<ImportFile> 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<ImportFile> 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);
}
/// <summary>The safety rule of «Sposta»: hash the copy as it is on disk now; delete the original only on a match.</summary>
private async Task<ImportFile> 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<Stream?> 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<Stream> 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;
}
}
/// <summary>Removes an entry this import created when it ended up without any file (identical content found).</summary>
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);
}
}
/// <summary>The library extension: the detected format's (".jpeg" becomes ".jpg"), or the file's own for unknown ones.</summary>
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<ImportFile> SaveAsync(ImportFile file) => SaveCoreAsync(file);
private async Task<ImportFile> 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; }
}
}
+169
View File
@@ -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;
/// <summary>
/// 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 <c>_febe.jsonl</c> lines are made the same way.
/// </summary>
public sealed record ImportEnvironment
{
public required IFebeStorage Storage { get; init; }
/// <summary>Library folder and account folders.</summary>
public required LibraryLayout Layout { get; init; }
/// <summary>The two naming schemes of the library settings.</summary>
public LibraryNaming Naming { get; init; } = LibraryNaming.Default;
public required AccountJournal Journal { get; init; }
public required IClock Clock { get; init; }
public ThumbnailStore? Thumbnails { get; init; }
/// <summary>
/// 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).
/// </summary>
public PerceptualHashIndex? HashIndex { get; init; }
/// <summary>ffmpeg, for thumbnails of imported videos (spec §8.4). Null: the neutral tile.</summary>
public VideoFrameExtractor? Frames { get; init; }
/// <summary>ffprobe, an optional extra for videos the hand-written reader does not cover.</summary>
public IVideoMetadataProbe? VideoProbe { get; init; }
/// <summary>«Imposta la data del file a quella di pubblicazione» (library setting).</summary>
public bool SetFileTimeToPublication { get; init; } = true;
/// <summary>Where sources may be chosen (Docker: <c>/importa</c>).</summary>
public ImportSourceOptions Sources { get; init; } = ImportSourceOptions.AnyFolder;
/// <summary>The Data folder: a source may not overlap it.</summary>
public string? DataFolder { get; init; }
/// <summary>Read-only detection of sources.</summary>
public ISourceAccessProbe? AccessProbe { get; init; }
/// <summary>Reading, hashing and deleting source files.</summary>
public IImportFileSystem FileSystem { get; init; } = ImportFileSystem.Instance;
/// <summary>Files analysed at the same time (hashing and decoding).</summary>
public int Parallelism { get; init; } = Math.Clamp(Environment.ProcessorCount, 1, 4);
/// <summary>The checker of sources for this environment.</summary>
public ImportSources CreateSources() => new(Sources, Layout.Root, DataFolder, AccessProbe);
}
/// <summary>
/// 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.
/// </summary>
public interface IImportFileSystem
{
/// <summary>Opens a source file for reading only.</summary>
Stream OpenRead(string fullPath);
/// <summary>SHA-256 (lowercase hex) of a file as it is on disk now.</summary>
Task<string> ComputeSha256Async(string fullPath, CancellationToken ct);
/// <summary>Deletes an original of «Sposta», after its copy was verified.</summary>
void DeleteOriginal(string fullPath);
}
/// <summary>The real file system.</summary>
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<string> 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);
}
/// <summary>
/// Choices of an import that have no column in <c>import_run</c>, kept in the <c>setting</c> table under
/// <c>importazione.{id}.*</c>: 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).
/// </summary>
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<bool> 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);
/// <summary>Folder → user name of the new «Solo archivio» account it goes to.</summary>
public static async Task<IReadOnlyDictionary<string, string>> GetNewAccountsAsync(ISettingsStore store, long runId, CancellationToken ct)
{
var text = await store.GetAsync(NewAccountsKey(runId), ct).ConfigureAwait(false);
var result = new Dictionary<string, string>(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<string>() 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<string, string> 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<string, string?> { [StogramKey(runId)] = null, [NewAccountsKey(runId)] = null }, ct);
}
+224
View File
@@ -0,0 +1,224 @@
using Febe.Core.Domain;
namespace Febe.Core.Import;
/// <summary>Choices made when an import starts (step 1).</summary>
public sealed record ImportAnalysisOptions
{
/// <summary>
/// Turns on the 4K Stogram recognizer, which is <b>an unverified hypothesis</b> (spec §9.6): off by default. The
/// interface may offer it when <see cref="ImportSourceInfo.LooksLikeStogram"/> is true, saying that names are read
/// by a guess still to be checked on Alberto's real files.
/// </summary>
public bool StogramHypothesis { get; init; }
}
/// <summary>The phase of an import job.</summary>
public enum ImportPhase
{
/// <summary>«Elenco dei file»: the source is listed (read-only).</summary>
Listing,
/// <summary>«Analisi»: type, hashes, dates and comparison with the library.</summary>
Analyzing,
/// <summary>«Copia»: copy or move with verification.</summary>
Copying,
/// <summary>The job ended (finished, interrupted or failed: see the run state).</summary>
Finished,
}
/// <summary>Progress of an import job, for the bar of steps 2 and 4.</summary>
/// <param name="RunId">The import.</param>
/// <param name="Phase">What is running.</param>
/// <param name="FilesDone">Files analysed (or handled by the copy) so far, earlier sessions included.</param>
/// <param name="FilesTotal">Files of the source (known after the listing).</param>
/// <param name="BytesDone">Bytes of the files done.</param>
/// <param name="BytesTotal">Bytes of all the files.</param>
/// <param name="CurrentFile">The file being read, relative to the source.</param>
/// <param name="Outcomes">Counts by outcome so far (analysis).</param>
/// <param name="Copied">Files copied or moved so far (copy).</param>
/// <param name="UpdatedAt">When this snapshot was taken.</param>
public sealed record ImportProgress(
long RunId,
ImportPhase Phase,
int FilesDone,
int FilesTotal,
long BytesDone,
long BytesTotal,
string? CurrentFile,
IReadOnlyDictionary<ImportOutcome, int> Outcomes,
int Copied,
DateTimeOffset UpdatedAt)
{
/// <summary>Done fraction between 0 and 1 (by bytes when known, else by files).</summary>
public double Fraction => BytesTotal > 0 ? Math.Clamp((double)BytesDone / BytesTotal, 0, 1)
: FilesTotal > 0 ? Math.Clamp((double)FilesDone / FilesTotal, 0, 1) : 0;
}
/// <summary>Where the files of a source folder go (the «Va in» menu of mockup 09).</summary>
public enum FolderTargetKind
{
/// <summary>«Scegli un account…»: the folder's files stay out of the import.</summary>
None,
/// <summary>An account already in Febe.</summary>
Existing,
/// <summary>«Nuovo account, solo archivio»: created when the copy starts.</summary>
NewArchiveAccount,
}
/// <summary>The association of a source folder.</summary>
/// <param name="Kind">None, existing account or new «Solo archivio» account.</param>
/// <param name="AccountId">The existing account.</param>
/// <param name="Username">The account's user name (existing or to create).</param>
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);
}
/// <summary>A row of the «Cartelle e account» table (mockup 09).</summary>
/// <param name="Folder">Folder relative to the source ('' for the source itself): the key to pass back.</param>
/// <param name="DisplayName">Name shown («marta.demo», «Foto sparse»).</param>
/// <param name="ProbableAccount">Account guessed from the name, when it can be a user name.</param>
/// <param name="Files">Files of the folder.</param>
/// <param name="Bytes">Their size.</param>
/// <param name="New">«Nuovi».</param>
/// <param name="AlreadyInLibrary">«Già presenti» (identical copies in the source included).</param>
/// <param name="ProbableDuplicates">«Doppioni probabili».</param>
/// <param name="Unrecognized">«Non riconosciuti».</param>
/// <param name="Recognized">Files whose Instagram identifier or code is known.</param>
/// <param name="Target">Where the folder goes.</param>
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)
{
/// <summary>The folder has no account: its files stay out (spec §9.4).</summary>
public bool IsBlocked => Target.Kind == FolderTargetKind.None;
}
/// <summary>The summary at the top of step 3 (mockup 09).</summary>
/// <param name="Run">The import.</param>
/// <param name="DisplayPath">The source as shown.</param>
/// <param name="Files">Files of the source.</param>
/// <param name="Bytes">Their size.</param>
/// <param name="ByOutcome">Counts per outcome.</param>
/// <param name="Recognized">Files whose identifier or code is known: Febe will not download them again (§9.5).</param>
/// <param name="PendingDuplicates">Probable duplicates still waiting for a decision.</param>
/// <param name="Folders">The folders with their association.</param>
/// <param name="AnalysisDuration">From the start of the import to the end of the analysis.</param>
/// <param name="StogramHypothesis">The 4K Stogram hypothesis recognizer was used.</param>
/// <param name="Copied">Files already copied or moved by this import.</param>
public sealed record ImportReviewSummary(
ImportRun Run,
string DisplayPath,
int Files,
long Bytes,
IReadOnlyDictionary<ImportOutcome, int> ByOutcome,
int Recognized,
int PendingDuplicates,
IReadOnlyList<ImportFolderReview> Folders,
TimeSpan? AnalysisDuration,
bool StogramHypothesis,
int Copied)
{
/// <summary>«Sposta» is offered only for writable sources.</summary>
public bool CanMove => !Run.SourceReadOnly;
/// <summary>The line under the title: «12.480 file, 38 GB, analizzati in 18 minuti. Nessun file è stato ancora copiato.»</summary>
public string Headline => ImportText.Headline(Files, Bytes, AnalysisDuration, Copied);
}
/// <summary>One side of a probable duplicate, as the comparison panel shows it.</summary>
/// <param name="InLibrary">A library file («In libreria»); otherwise a file of the source («Da importare»).</param>
/// <param name="MediaId">The library file.</param>
/// <param name="ImportFileId">The file of the source.</param>
/// <param name="Username">Account of the library file, or destination of the source file.</param>
/// <param name="Path">Path relative to the account folder (library) or to the source.</param>
/// <param name="Kind">Photo or video.</param>
/// <param name="Width">Width in pixels.</param>
/// <param name="Height">Height in pixels.</param>
/// <param name="Bytes">Size.</param>
/// <param name="Date">Publication (library) or found date (source).</param>
/// <param name="Sha256">SHA-256: the library thumbnail key.</param>
/// <param name="HasThumbnail">A library thumbnail exists for <see cref="Sha256"/>.</param>
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);
/// <summary>A probable duplicate to decide (right panel of mockup 09). No choice is made in advance.</summary>
/// <param name="Pair">The stored pair (its <see cref="DuplicatePair.Decision"/> is Pending until Alberto chooses).</param>
/// <param name="Existing">The file already there (library, or the first file met in the source).</param>
/// <param name="Candidate">The file of the source.</param>
/// <param name="CandidateIsLarger">The «Più grande» badge goes on the candidate (more pixels, then more bytes).</param>
public sealed record DuplicateCase(DuplicatePair Pair, DuplicateSide Existing, DuplicateSide Candidate, bool CandidateIsLarger)
{
/// <summary>Both sides are files of the source (a duplicate inside the source itself).</summary>
public bool InsideSource => !Existing.InLibrary;
}
/// <summary>What «Importa» would do now (the final button and the line next to it).</summary>
/// <param name="ToImport">Files that will be copied (replacements included).</param>
/// <param name="ToReplace">Of those, files that replace a smaller library file («Tieni il più grande»).</param>
/// <param name="Skipped">Files that will not be copied: already in the library, not recognized, decided against.</param>
/// <param name="LeftOutNoAccount">Files that stay out because their folder has no account.</param>
/// <param name="FoldersWithoutAccount">Folders without account that hold files to import.</param>
/// <param name="LeftOutUndecided">Files that wait for a decision on a probable duplicate.</param>
/// <param name="AlreadyDone">Files already copied or moved by this import.</param>
/// <param name="Bytes">Size of the files to import.</param>
/// <param name="Mode">Copia or Sposta.</param>
public sealed record ImportPlan(
int ToImport,
int ToReplace,
int Skipped,
int LeftOutNoAccount,
int FoldersWithoutAccount,
int LeftOutUndecided,
int AlreadyDone,
long Bytes,
ImportMode Mode)
{
/// <summary>The final button: «Importa 7.682 file».</summary>
public string ButtonLabel => ImportText.ImportButton(ToImport);
/// <summary>The line next to it: «1 cartella senza account: 1.438 file restano fuori», or null.</summary>
public string? LeftOutLabel => ImportText.LeftOut(FoldersWithoutAccount, LeftOutNoAccount, LeftOutUndecided);
}
/// <summary>Which pending pairs a decision applies to (the «Fai lo stesso per gli altri» box of mockup 09).</summary>
public enum DecisionScope
{
/// <summary>Only this pair.</summary>
ThisPair,
/// <summary>Every pair of this import still waiting, with the same reason (same identifier, or visually similar).</summary>
SameReason,
/// <summary>Every pair of this import still waiting.</summary>
AllPending,
}
+255
View File
@@ -0,0 +1,255 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Import;
/// <summary>What the copy does with one file.</summary>
internal enum PlannedAction
{
/// <summary>Already copied, moved or skipped by this import.</summary>
Done,
/// <summary>Not analysed (or unreadable): the copy ignores it.</summary>
NotAnalyzed,
/// <summary>Copied into the destination account.</summary>
Import,
/// <summary>Replaces a smaller library file: Alberto chose «Tieni il più grande» (rule 12).</summary>
Replace,
/// <summary>Not copied: already in the library, not a photo or video, or decided against.</summary>
Skip,
/// <summary>Stays out: the folder has no account.</summary>
WaitNoAccount,
/// <summary>Stays out: a probable duplicate waits for Alberto's decision.</summary>
WaitDecision,
}
/// <summary>The planned action for a file, with the note for the report.</summary>
internal sealed record PlannedFile(ImportFile File, PlannedAction Action, string? Note, long? ReplaceMediaId);
/// <summary>
/// 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.
/// <list type="bullet">
/// <item>«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);</item>
/// <item>a file with a pair still waiting for a decision stays out, and so does the other file of a pair inside the
/// source;</item>
/// <item>«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;</item>
/// <item>files of a folder without account stay out.</item>
/// </list>
/// </summary>
internal sealed class ImportPlanner
{
private readonly Dictionary<long, List<DuplicatePair>> _pairsByFile = [];
private readonly Dictionary<long, (PlannedAction Action, string Note)> _decided = [];
private readonly Dictionary<long, long> _replacements = [];
private readonly IReadOnlyDictionary<string, string> _newAccounts;
private ImportPlanner(IReadOnlyDictionary<string, string> newAccounts) => _newAccounts = newAccounts;
/// <summary>Loads pairs, sizes and the folders going to new accounts.</summary>
public static async Task<ImportPlanner> LoadAsync(IFebeStorage storage, long runId, IReadOnlyDictionary<long, ImportFile> files, CancellationToken ct)
{
var planner = new ImportPlanner(await ImportRunSettings.GetNewAccountsAsync(storage.Settings, runId, ct).ConfigureAwait(false));
var pairs = new List<DuplicatePair>();
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<long>())
{
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;
}
/// <summary>True when the folder of the file has (or will have) an account.</summary>
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);
}
/// <summary>
/// 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.
/// </summary>
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<long, long> _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<IReadOnlyList<long>> Groups() =>
_parent.Keys.ToList().GroupBy(Find).Select(g => (IReadOnlyList<long>)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;
}
}
}
+34
View File
@@ -0,0 +1,34 @@
using Febe.Core.Library;
using SkiaSharp;
namespace Febe.Core.Import;
/// <summary>In-memory previews of source photos for the comparison panel (nothing is written to disk).</summary>
internal static class ImportPreview
{
private const int JpegQuality = 82;
/// <summary>A JPEG of the image, upright, at most <paramref name="longSide"/> pixels; null when it cannot be decoded.</summary>
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();
}
}
+213
View File
@@ -0,0 +1,213 @@
using System.Globalization;
using System.Text;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Import;
/// <summary>How many files of an import concern an account.</summary>
public sealed record AccountCount(string Username, int Files);
/// <summary>A file of the report with its note.</summary>
public sealed record ReportNote(string Path, string Note);
/// <summary>The final report of an import, on screen (spec §9.4 «resoconto a schermo»).</summary>
/// <param name="Run">The import.</param>
/// <param name="DisplayPath">The source as shown.</param>
/// <param name="Files">Files of the source.</param>
/// <param name="Bytes">Their size.</param>
/// <param name="ByOutcome">Counts per outcome of the analysis.</param>
/// <param name="ByState">Counts per state now.</param>
/// <param name="Copied">Copied into the library (moved included).</param>
/// <param name="Moved">Of those, originals deleted after verification («Sposta»).</param>
/// <param name="Replaced">Of those, files that replaced a smaller library file.</param>
/// <param name="Skipped">Not copied: already in the library, not recognized, decided against.</param>
/// <param name="LeftOut">Still out: folder without account or duplicate without decision.</param>
/// <param name="Failed">Not succeeded (unreadable, changed, copy not verified).</param>
/// <param name="BytesCopied">Size of the copied files.</param>
/// <param name="ImportedByAccount">Copied files per destination account.</param>
/// <param name="AlreadyInLibraryByAccount">Where the «Già in libreria» files already are.</param>
/// <param name="Unrecognized">The files that are neither photos nor videos (at most <see cref="ImportReports.MaxListed"/>).</param>
/// <param name="Problems">Files that failed or need attention, with the reason (at most <see cref="ImportReports.MaxListed"/>).</param>
public sealed record ImportReport(
ImportRun Run,
string DisplayPath,
int Files,
long Bytes,
IReadOnlyDictionary<ImportOutcome, int> ByOutcome,
IReadOnlyDictionary<ImportFileState, int> ByState,
int Copied,
int Moved,
int Replaced,
int Skipped,
int LeftOut,
int Failed,
long BytesCopied,
IReadOnlyList<AccountCount> ImportedByAccount,
IReadOnlyList<AccountCount> AlreadyInLibraryByAccount,
IReadOnlyList<string> Unrecognized,
IReadOnlyList<ReportNote> Problems);
/// <summary>
/// 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.
/// </summary>
public sealed class ImportReports(ImportEnvironment env)
{
/// <summary>The longest lists of the on-screen report (the CSV has every file).</summary>
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<ImportReport> 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<string, int>(StringComparer.OrdinalIgnoreCase);
var already = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var unrecognized = new List<string>();
var problems = new List<ReportNote>();
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);
}
/// <summary>Suggested name of the CSV file: «importazione-2026-10-13-12.csv».</summary>
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");
}
/// <summary>Writes one row per file to <paramref name="destination"/> (left open): ';', UTF-8 with BOM, CRLF.</summary>
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);
}
/// <summary>A CSV line: fields separated by ';', quoted when needed.</summary>
internal static string Line(IReadOnlyList<string> fields) => string.Join(';', fields.Select(Field));
/// <summary>
/// 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.
/// </summary>
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<ImportReportRow> 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<AccountCount> Sorted(Dictionary<string, int> counts) =>
counts.OrderByDescending(c => c.Value).ThenBy(c => c.Key, StringComparer.Ordinal).Select(c => new AccountCount(c.Key, c.Value)).ToList();
}
+400
View File
@@ -0,0 +1,400 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Import;
/// <summary>
/// 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.
/// </summary>
public sealed class ImportReview(ImportEnvironment env)
{
private readonly SemaphoreSlim _settingsGate = new(1, 1);
/// <summary>The summary of an analysed import.</summary>
public async Task<ImportReviewSummary> 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]);
}
/// <summary>The rows of «Cartelle e account».</summary>
public async Task<IReadOnlyList<ImportFolderReview>> ListFoldersAsync(long runId, CancellationToken ct = default) =>
await ListFoldersAsync(await GetRunAsync(runId, ct).ConfigureAwait(false), ct).ConfigureAwait(false);
private async Task<IReadOnlyList<ImportFolderReview>> 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<ImportFolderReview>();
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;
}
/// <summary>
/// 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).
/// </summary>
/// <exception cref="ArgumentException">The account does not exist or the name cannot be an Instagram user name.</exception>
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<string, string>(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();
}
}
/// <summary>«Copia» or «Sposta».</summary>
/// <exception cref="InvalidOperationException">«Sposta» on a read-only source.</exception>
public async Task<ImportRun> 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;
}
/// <summary>
/// The probable duplicates of an import, both sides described, in creation order. <paramref name="pendingOnly"/>
/// gives the ones still to decide.
/// </summary>
public async Task<IReadOnlyList<DuplicateCase>> 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<DuplicateCase>(pairs.Count);
foreach (var pair in pairs)
{
cases.Add(await DescribeAsync(pair, ct).ConfigureAwait(false));
}
return cases;
}
/// <summary>One probable duplicate, both sides described.</summary>
public async Task<DuplicateCase?> 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;
/// <summary>
/// Records Alberto's decision on a probable duplicate and, with <paramref name="scope"/>, 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.
/// </summary>
/// <exception cref="ArgumentException">The decision is «Pending», or the pair is not of this import.</exception>
public async Task<int> 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<DuplicatePair> { 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;
}
/// <summary>Takes back a decision: the pair waits again (no choice made).</summary>
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);
}
}
/// <summary>What «Importa» would do now: files to import, to replace, skipped, left out and why.</summary>
public async Task<ImportPlan> GetPlanAsync(long runId, CancellationToken ct = default)
{
var run = await GetRunAsync(runId, ct).ConfigureAwait(false);
var files = new Dictionary<long, ImportFile>();
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<string>(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);
}
/// <summary>Opens a file of the source for reading (the comparison panel shows it).</summary>
public async Task<Stream> 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));
}
/// <summary>
/// A JPEG preview of a photo of the source, at most <paramref name="longSide"/> pixels (not stored: the source file
/// may never enter the library). Null for videos and formats that cannot be decoded.
/// </summary>
public async Task<byte[]?> 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<DuplicateCase> 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<DuplicateSide> 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<ImportRun> 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.");
}
}
}
+362
View File
@@ -0,0 +1,362 @@
using System.Diagnostics;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Import;
/// <summary>
/// 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 <see cref="ProgressChanged"/> or
/// <see cref="GetProgressAsync"/> and stops them with <see cref="InterruptAsync"/>. Every state lives in the database:
/// after a restart call <see cref="RecoverAsync"/> once, then <see cref="ResumeAsync"/> continues where it stopped.
/// See <c>src/Febe.Core/Import/LEGGIMI.md</c>.
/// </summary>
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);
}
/// <summary>
/// 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.
/// </summary>
public event EventHandler<ImportProgress>? ProgressChanged;
/// <summary>Step 1: checking sources.</summary>
public ImportSources Sources { get; }
public ImportAnalyzer Analyzer { get; }
public ImportCopier Copier { get; }
public ImportReview Review { get; }
public ImportReports Reports { get; }
/// <summary>The import whose job is running, if any.</summary>
public long? ActiveRunId
{
get
{
lock (_gate)
{
return _job is { Task.IsCompleted: false } job ? job.RunId : null;
}
}
}
/// <summary>The last error of a background job that could not be stored with the import (normally null).</summary>
public string? LastJobError { get; private set; }
/// <summary>
/// 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.
/// </summary>
public async Task<int> 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;
}
/// <summary>Imports, newest first (to offer «Riprendi» on an unfinished one).</summary>
public Task<IReadOnlyList<ImportRun>> ListRunsAsync(CancellationToken ct = default) => _env.Storage.Imports.ListRunsAsync(ct);
public Task<ImportRun?> GetRunAsync(long runId, CancellationToken ct = default) => _env.Storage.Imports.GetRunAsync(runId, ct);
/// <summary>Step 1: checks a folder. Throws <see cref="ImportSourceException"/> with the reason in Italian.</summary>
public ImportSourceInfo InspectSource(string path) => Sources.Inspect(path);
/// <summary>Step 1 in Docker: the subfolders of <c>/importa</c> (or of one of its subfolders).</summary>
public IReadOnlyList<SourceFolderChoice> BrowseSources(string? path = null) => Sources.Browse(path);
/// <summary>Step 1 → 2: records the import and starts the analysis in the background.</summary>
/// <exception cref="ImportSourceException">The folder cannot be used.</exception>
/// <exception cref="InvalidOperationException">Another import job is running.</exception>
public async Task<ImportRun> 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;
}
/// <summary>Continues an interrupted analysis or copy in the background.</summary>
public async Task<ImportRun> 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;
}
/// <summary>
/// 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 <paramref name="mode"/> the mode is set first.
/// </summary>
public async Task<ImportRun> 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;
}
/// <summary>«Interrompi»: stops the running job of this import and waits until its state is saved.</summary>
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);
}
/// <summary>Waits for the running job of this import (if any) to end, however it ends; returns the import.</summary>
public async Task<ImportRun?> 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);
}
/// <summary>The progress of an import: live while its job runs, otherwise from the database.</summary>
public async Task<ImportProgress> 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<ImportReviewSummary> 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<ImportRun> SetModeAsync(long runId, ImportMode mode, CancellationToken ct = default) => Review.SetModeAsync(runId, mode, ct);
public Task<IReadOnlyList<DuplicateCase>> ListDuplicatesAsync(long runId, bool pendingOnly = true, long afterPairId = 0, int limit = 50, CancellationToken ct = default) =>
Review.ListDuplicatesAsync(runId, pendingOnly, afterPairId, limit, ct);
public Task<int> DecideAsync(long runId, long pairId, DuplicateDecision decision, DecisionScope scope = DecisionScope.ThisPair, CancellationToken ct = default) =>
Review.DecideAsync(runId, pairId, decision, scope, ct);
public Task<ImportPlan> GetPlanAsync(long runId, CancellationToken ct = default) => Review.GetPlanAsync(runId, ct);
// Step 4.
public Task<ImportReport> 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);
/// <summary>
/// «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.
/// </summary>
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<IProgress<ImportProgress>, 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<ImportOutcome, int>(), 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<ImportProgress>
{
private ImportPhase? _phase;
public void Report(ImportProgress value)
{
var phaseChanged = _phase != value.Phase;
_phase = value.Phase;
owner.Publish(value, phaseChanged);
}
}
}
+373
View File
@@ -0,0 +1,373 @@
using Febe.Core.Library;
namespace Febe.Core.Import;
/// <summary>Where sources may be chosen (spec §9.1 «Sorgente», §11).</summary>
public sealed record ImportSourceOptions
{
/// <summary>
/// Root of the sources. In Docker the volume <c>/importa</c>: a source is that folder or one of its subfolders.
/// Null on Windows: any folder Alberto chooses.
/// </summary>
public string? Root { get; init; }
/// <summary>
/// The root is mounted read-only (the <c>/importa</c> volume, spec §11): «Sposta» is never offered below it, whatever
/// the mount table says.
/// </summary>
public bool RootIsReadOnly { get; init; }
/// <summary>Docker: sources under <paramref name="root"/>, read-only.</summary>
public static ImportSourceOptions Docker(string root = "/importa") => new() { Root = root, RootIsReadOnly = true };
/// <summary>Windows (and development): any folder.</summary>
public static ImportSourceOptions AnyFolder { get; } = new();
}
/// <summary>What step 1 knows about a chosen source.</summary>
/// <param name="FullPath">Full path of the folder.</param>
/// <param name="DisplayPath">Path shown to Alberto (relative to the root in Docker, e.g. «/importa/4K Stogram»).</param>
/// <param name="Name">Folder name.</param>
/// <param name="ReadOnly">The source cannot be written: «Sposta» does not appear (spec §9.4).</param>
/// <param name="LooksLikeFebeLibrary">Account folders with <c>_febe.jsonl</c> were found.</param>
/// <param name="LooksLikeStogram">
/// A 4K Stogram database file is present (only its existence is checked): the interface may offer the hypothesis
/// recognizer, saying it is unverified.
/// </param>
/// <param name="RootIsAccount">The folder itself looks like one account (see <see cref="SourceLayout"/>).</param>
/// <param name="Folders">First-level subfolders.</param>
public sealed record ImportSourceInfo(
string FullPath,
string DisplayPath,
string Name,
bool ReadOnly,
bool LooksLikeFebeLibrary,
bool LooksLikeStogram,
bool RootIsAccount,
IReadOnlyList<string> Folders)
{
/// <summary>«Sposta» is offered only for writable sources.</summary>
public bool CanMove => !ReadOnly;
}
/// <summary>A folder offered by the source picker (Docker: below <c>/importa</c>).</summary>
/// <param name="Name">Folder name.</param>
/// <param name="Path">Path to pass back to <see cref="ImportSources.Inspect"/> (relative to the root when there is one).</param>
/// <param name="HasSubfolders">The folder has subfolders to open.</param>
public sealed record SourceFolderChoice(string Name, string Path, bool HasSubfolders);
/// <summary>A source that cannot be used; the message (Italian) says why and what to do.</summary>
public sealed class ImportSourceException : Exception
{
public ImportSourceException()
{
}
public ImportSourceException(string message)
: base(message)
{
}
public ImportSourceException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>Tells whether a folder can be written, without writing into it.</summary>
public interface ISourceAccessProbe
{
bool IsReadOnly(string fullPath);
}
/// <summary>
/// Read-only detection that never writes into the source: on Linux the mount options of the file system that holds the
/// folder (<c>ro</c>, as for a Docker volume mounted with <c>:ro</c>); 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).
/// </summary>
public sealed class SystemSourceAccessProbe(Func<string?>? readMounts = null) : ISourceAccessProbe
{
private readonly Func<string?> _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));
}
/// <summary>True when the mount that contains <paramref name="fullPath"/> has the <c>ro</c> option.</summary>
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;
}
}
}
/// <summary>
/// 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 <c>_febe.jsonl</c> may be imported, as the rebuild suggests).
/// </summary>
public sealed class ImportSources
{
private static readonly StringComparison PathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
private static readonly HashSet<string> 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;
/// <param name="options">Root and read-only flag.</param>
/// <param name="libraryRoot">The library folder (a source may not contain it).</param>
/// <param name="dataRoot">The Data folder (a source may not overlap it).</param>
/// <param name="probe">Read-only detection; <see cref="SystemSourceAccessProbe"/> by default.</param>
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));
}
/// <summary>Full path of the root of the sources (Docker), or null (any folder).</summary>
public string? Root { get; }
/// <summary>Enumeration used everywhere on sources: hidden, system files and links are skipped.</summary>
public static EnumerationOptions Enumeration(bool recursive) => new()
{
RecurseSubdirectories = recursive,
IgnoreInaccessible = true,
AttributesToSkip = FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReparsePoint,
ReturnSpecialDirectories = false,
MatchType = MatchType.Simple,
};
/// <summary>
/// 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.
/// </summary>
public static bool IsIgnoredFile(string fileName)
{
ArgumentNullException.ThrowIfNull(fileName);
return IgnoredNames.Contains(fileName) || SafeFileWriter.IsTemporaryFile(fileName) || fileName.StartsWith("._", StringComparison.Ordinal);
}
/// <summary>The full path of a chosen folder, checked.</summary>
/// <exception cref="ImportSourceException">The folder cannot be used; the message says why.</exception>
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;
}
/// <summary>Checks a chosen folder and tells what it looks like (step 1).</summary>
/// <exception cref="ImportSourceException">The folder cannot be used.</exception>
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);
}
/// <summary>True when the folder cannot be written (configured read-only root, or the system says so).</summary>
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);
}
/// <summary>
/// Subfolders offered by the picker. With a root (Docker) <paramref name="path"/> is relative to it and the result
/// paths are relative too; without a root it is an absolute folder.
/// </summary>
public IReadOnlyList<SourceFolderChoice> 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();
}
/// <summary>The path shown to Alberto: in Docker relative to the root, with the root's name in front.</summary>
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;
}
+143
View File
@@ -0,0 +1,143 @@
using Febe.Core.Domain;
using Febe.Core.Engine;
namespace Febe.Core.Import;
/// <summary>
/// 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).
/// </summary>
public static class ImportText
{
/// <summary>Name of an outcome, as in the four boxes of mockup 09.</summary>
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(),
};
/// <summary>The line under each box of mockup 09.</summary>
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,
};
/// <summary>State of a file.</summary>
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(),
};
/// <summary>Where a date came from.</summary>
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,
};
/// <summary>A kind, singular, for tables.</summary>
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,
};
/// <summary>The three choices of the comparison panel.</summary>
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",
};
/// <summary>«Copia» or «Sposta».</summary>
public static string Mode(ImportMode mode) => mode == ImportMode.Move ? "Sposta" : "Copia";
/// <summary>The line next to the mode switch.</summary>
public static string ModeHint(ImportMode mode) => mode == ImportMode.Move
? "Gli originali si eliminano solo dopo aver verificato la copia."
: "Gli originali restano dove sono.";
/// <summary>«Importa 7.682 file».</summary>
public static string ImportButton(int files) => "Importa " + ItalianText.Number(files) + " file";
/// <summary>«1 cartella senza account: 1.438 file restano fuori», with the files waiting for a decision; null when nothing stays out.</summary>
public static string? LeftOut(int foldersWithoutAccount, int filesWithoutAccount, int undecided)
{
var parts = new List<string>();
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);
}
/// <summary>«12.480 file, 38 GB, analizzati in 18 minuti. Nessun file è stato ancora copiato.»</summary>
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;
}
/// <summary>«1 file», «1.438 file».</summary>
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. Rifai l'analisi di questa 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.";
}
+170
View File
@@ -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 <id contenuto>_<id utente>.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.
+242
View File
@@ -0,0 +1,242 @@
using System.Buffers.Binary;
using System.Text;
using Febe.Core.Domain;
namespace Febe.Core.Import;
/// <summary>A file type recognized from the content.</summary>
/// <param name="Kind">Photo or video.</param>
/// <param name="ContentType">Media type, e.g. "image/jpeg".</param>
/// <param name="Extension">Extension used for the library name, with the dot (e.g. ".jpg").</param>
/// <param name="Format">Short format name for the report («JPEG», «MP4», ...).</param>
public sealed record DetectedType(MediaKind Kind, string ContentType, string Extension, string Format)
{
/// <summary>True for the ISO base media family (MP4, MOV, 3GP): creation time and size come from the <c>moov</c> box.</summary>
public bool IsIsoMedia => ContentType is "video/mp4" or "video/quicktime" or "video/3gpp" or "video/3gpp2";
}
/// <summary>
/// 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.
/// </summary>
public static class MediaSniffer
{
/// <summary>Bytes to read from the start of a file for <see cref="Detect"/>.</summary>
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<string> HeifBrands = new(StringComparer.Ordinal)
{
"heic", "heix", "heim", "heis", "hevc", "hevx", "hevm", "hevs", "mif1", "msf1", "mif2", "MiHE", "MiHB",
};
private static readonly HashSet<string> AvifBrands = new(StringComparer.Ordinal) { "avif", "avis" };
private static readonly HashSet<string> 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<string> ThreeGpBrands = new(StringComparer.Ordinal)
{
"3gp4", "3gp5", "3gp6", "3gp7", "3gs6", "3gs7", "3ge6", "3ge7", "3gg6",
};
private static readonly HashSet<string> AudioBrands = new(StringComparer.Ordinal) { "M4A ", "M4B ", "M4P ", "F4A ", "F4B " };
/// <summary>Top-level atoms that may open a QuickTime file without <c>ftyp</c> (old cameras).</summary>
private static readonly HashSet<string> QuickTimeAtoms = new(StringComparer.Ordinal) { "moov", "mdat", "wide", "free", "skip", "pnot" };
/// <summary>Extensions of raw camera formats built on TIFF: kept as they are in library names.</summary>
private static readonly HashSet<string> TiffFamilyExtensions = new(StringComparer.OrdinalIgnoreCase)
{
".tif", ".tiff", ".dng", ".cr2", ".nef", ".nrw", ".arw", ".srf", ".sr2", ".orf", ".rw2", ".pef", ".raf", ".erf", ".3fr",
};
/// <summary>The type of a file from its first bytes; null when it is neither a photo nor a video.</summary>
/// <param name="head">The first bytes of the file (at least 12; <see cref="HeadLength"/> recommended).</param>
/// <param name="originalExtension">The file's own extension, used only to name raw camera formats.</param>
public static DetectedType? Detect(ReadOnlySpan<byte> 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;
}
/// <summary>Reads the first bytes of a file (read-only) and detects its type.</summary>
public static DetectedType? DetectFile(string path)
{
Span<byte> 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<byte> head)
{
var boxSize = (int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(head), (uint)head.Length);
var brands = new List<string> { 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<byte> bytes) => Encoding.Latin1.GetString(bytes);
}
+222
View File
@@ -0,0 +1,222 @@
using System.Buffers.Binary;
namespace Febe.Core.Import;
/// <summary>What the <c>moov</c> box of an MP4 or QuickTime file says.</summary>
/// <param name="CreatedAt">Creation time of the movie header (<c>mvhd</c>), when plausible.</param>
/// <param name="Duration">Duration from <c>mvhd</c>.</param>
/// <param name="Width">Display width of the first video track (rotation applied).</param>
/// <param name="Height">Display height of the first video track (rotation applied).</param>
public sealed record Mp4Info(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height);
/// <summary>
/// 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 (<c>mdat</c>) 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.
/// </summary>
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);
/// <summary>The largest <c>moov</c> box read into memory.</summary>
private const long MaxMoovBytes = 64L * 1024 * 1024;
private const int MaxTopLevelBoxes = 10_000;
/// <summary>Reads a file (read-only). Null when no <c>moov</c> box is found.</summary>
/// <param name="path">The file.</param>
/// <param name="now">Current time: creation times after it (by more than a day) are ignored.</param>
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);
}
/// <summary>Reads a seekable stream from its start. Null when no <c>moov</c> box is found.</summary>
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<byte> 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;
}
/// <summary>Parses the content of a <c>moov</c> box.</summary>
internal static Mp4Info? ParseMoov(ReadOnlySpan<byte> 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<byte> 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<byte> 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);
}
/// <summary>Child boxes of a box body: type, start and length of each body.</summary>
private static List<(string Type, int Start, int Length)> Children(ReadOnlySpan<byte> 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;
}
}
+602
View File
@@ -0,0 +1,602 @@
using System.Text;
using System.Text.RegularExpressions;
using Febe.Core.Domain;
using Febe.Core.Library;
namespace Febe.Core.Import;
/// <summary>
/// How a source is divided into folders that each go to one account (mockup 09, «Cartelle e account»).
/// <para>
/// 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. <c>/importa/marta.demo</c>). 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.
/// </para>
/// </summary>
public sealed partial class SourceLayout
{
private static readonly HashSet<string> 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<string> firstLevelFolders)
{
Root = root;
RootName = Path.GetFileName(Path.TrimEndingDirectorySeparator(root)) is { Length: > 0 } name ? name : root;
RootIsAccount = rootIsAccount;
FirstLevelFolders = firstLevelFolders;
}
/// <summary>Full path of the source folder.</summary>
public string Root { get; }
/// <summary>Name of the source folder.</summary>
public string RootName { get; }
/// <summary>The source folder itself is one unit (one account).</summary>
public bool RootIsAccount { get; }
/// <summary>First-level subfolders, by name.</summary>
public IReadOnlyList<string> FirstLevelFolders { get; }
/// <summary>Looks at the first level of a source (read-only).</summary>
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<string>()
.Order(StringComparer.Ordinal)
.ToList();
return new SourceLayout(full, folders.TrueForAll(IsStructural), folders);
}
/// <summary>A layout without looking at the disk (tests, demo data).</summary>
public static SourceLayout Create(string root, bool rootIsAccount, IReadOnlyList<string>? firstLevelFolders = null) =>
new(Path.GetFullPath(root), rootIsAccount, firstLevelFolders ?? []);
/// <summary>Folders of the source that are units, relative ('' for the source folder itself).</summary>
public IReadOnlyList<string> UnitFolders => RootIsAccount ? [string.Empty] : [string.Empty, .. FirstLevelFolders];
/// <summary>The unit folder of a file and its path inside that folder ('/' separated).</summary>
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)..]);
}
/// <summary>Full path of a unit folder.</summary>
public string FolderPath(string folder) => folder.Length == 0 ? Root : LibraryLayout.FullPath(Root, folder);
/// <summary>Name shown for a unit folder: its own name, or the source name for the source itself.</summary>
public string DisplayName(string folder) => folder.Length == 0 ? RootName : folder;
/// <summary>The name of the account folder a unit stands for, or null for loose files at the top of a multi-account source.</summary>
public string? AccountFolderName(string folder) => folder.Length > 0 ? folder : RootIsAccount ? RootName : null;
/// <summary>True for folder names that describe the content (kind, year, month), not an account.</summary>
public static bool IsStructural(string name)
{
var normalized = Normalize(name);
return StructuralNames.Contains(normalized) || YearOrMonth().IsMatch(normalized);
}
/// <summary>
/// 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»).
/// </summary>
public static (EntryKind? Kind, string? HighlightTitle) KindFromFolders(IReadOnlyList<string> 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);
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>Lowercase, without accents, single spaces (underscores and dashes count as spaces).</summary>
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}(?<!\.)$", RegexOptions.CultureInvariant)]
private static partial Regex Username();
}
/// <summary>A file of a source as the recognizers see it.</summary>
public sealed class ImportFileContext
{
/// <param name="layout">The source.</param>
/// <param name="relativePath">Path relative to the source, '/' separated.</param>
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; }
/// <summary>Path relative to the source, '/' separated.</summary>
public string RelativePath { get; }
/// <summary>The unit folder ('' for the source itself).</summary>
public string Folder { get; }
/// <summary>Path inside the unit folder, '/' separated.</summary>
public string PathInFolder { get; }
public string FileName { get; }
/// <summary>Folders between the unit folder and the file.</summary>
public IReadOnlyList<string> Directories { get; }
/// <summary>The name without extension and without the « (2)» a copy may carry.</summary>
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;
}
}
/// <summary>
/// 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 <see cref="object.ToString"/>.
/// </summary>
public sealed record FileHints
{
/// <summary>Name of the recognizer that gave the identity (<see cref="IImportRecognizer.Name"/>).</summary>
public string? Recognizer { get; init; }
/// <summary>The identity comes from an unverified hypothesis (4K Stogram, spec §9.6).</summary>
public bool Hypothesis { get; init; }
public DateTimeOffset? Date { get; init; }
/// <summary><see cref="ImportDateSource.FileName"/> or <see cref="ImportDateSource.Journal"/>.</summary>
public ImportDateSource? DateSource { get; init; }
/// <summary>Only the day was known.</summary>
public bool DateIsDayOnly { get; init; }
/// <summary>Instagram identifier of the entry.</summary>
public string? InstagramId { get; init; }
/// <summary>Instagram identifier of this item of a series.</summary>
public string? MediaInstagramId { get; init; }
/// <summary>Post code (short code).</summary>
public string? Code { get; init; }
/// <summary>Position in the series (<c>{n}</c>).</summary>
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; }
/// <summary>Caption (Febe journal only). Never logged.</summary>
public string? Caption { get; init; }
public string? AuthorUsername { get; init; }
public string? AuthorInstagramId { get; init; }
/// <summary>These hints, with the missing fields taken from <paramref name="fallback"/>.</summary>
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;
}
}
/// <summary>
/// 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.
/// </summary>
public interface IImportRecognizer
{
/// <summary>Stable name, e.g. «febe».</summary>
string Name { get; }
/// <summary>Name for Alberto, in Italian.</summary>
string Label { get; }
/// <summary>The recognizer rests on an unverified hypothesis.</summary>
bool IsHypothesis { get; }
/// <summary>Reads what it needs from the source once (e.g. the <c>_febe.jsonl</c> files), read-only.</summary>
Task PrepareAsync(SourceLayout layout, CancellationToken ct);
/// <summary>The hints for a file, or null when the file is not of this kind.</summary>
FileHints? Recognize(ImportFileContext file);
}
/// <summary>The recognizers of an analysis, in order of trust; the generic one runs last and always answers.</summary>
public sealed class ImportRecognizers
{
private readonly IReadOnlyList<IImportRecognizer> _items;
public ImportRecognizers(IReadOnlyList<IImportRecognizer> items)
{
ArgumentNullException.ThrowIfNull(items);
_items = items;
}
public IReadOnlyList<IImportRecognizer> Items => _items;
/// <summary>Febe, then (only when asked) the 4K Stogram hypothesis, then the generic recognizer.</summary>
public static ImportRecognizers Create(TimeZoneInfo zone, Func<DateTimeOffset> now, bool stogramHypothesis)
{
var list = new List<IImportRecognizer> { 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);
}
}
/// <summary>The hints of every recognizer that knows the file, the most trusted first.</summary>
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();
}
}
/// <summary>
/// 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).
/// </summary>
public sealed class GenericRecognizer(TimeZoneInfo zone, Func<DateTimeOffset> 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,
};
}
}
/// <summary>
/// Febe's own library as a source (spec §4.7, §8.5): account folders with <c>_febe.jsonl</c> give identifiers, exact
/// publication times, captions, positions and collections; names made by the default scheme
/// (<c>{data}_{ora}_{codice}_{n}</c> under <c>post</c>, <c>storie</c>, <c>evidenza/{raccolta}</c>, <c>taggati</c>,
/// <c>profilo</c>) give date, code and position even without the journal.
/// </summary>
public sealed partial class FebeRecognizer(TimeZoneInfo zone) : IImportRecognizer
{
private readonly Dictionary<string, Dictionary<string, (JournalLine Line, JournalFile File)>> _journals = new(StringComparer.Ordinal);
public string Name => "febe";
public string Label => "Libreria di Febe";
public bool IsHypothesis => false;
/// <summary>Unit folders whose journal was read.</summary>
public IReadOnlyCollection<string> 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<string, (JournalLine, JournalFile)>(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,
};
}
/// <summary>Kind from Febe's own folder names right below the account folder.</summary>
private static (EntryKind? Kind, string? Title) FebeKind(IReadOnlyList<string> 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(@"^(?<y>\d{4})-(?<mo>\d{2})-(?<d>\d{2})_(?<h>\d{2})-(?<mi>\d{2})-(?<s>\d{2})_(?<code>[A-Za-z0-9_\-]+)_(?<n>\d{1,3})$", RegexOptions.CultureInvariant)]
private static partial Regex DefaultName();
}
/// <summary>
/// <b>Hypothesis, not verified</b> (spec §9.6): 4K Stogram names its files «AAAA-MM-GG HH.MM.SS &lt;id contenuto&gt;_&lt;id
/// utente&gt;.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
/// <c>stogram.sqlite</c> before writing the recognizer for real. Until then it is off unless asked for
/// (<see cref="ImportAnalysisOptions.StogramHypothesis"/>), it is tested only on synthetic names, and it never opens
/// <c>stogram.sqlite</c>. The time in the name is read as local time (also a hypothesis).
/// </summary>
public sealed partial class StogramHypothesisRecognizer(TimeZoneInfo zone) : IImportRecognizer
{
/// <summary>Files that 4K Stogram keeps in its output folder (verified, spec §9.6). Their presence is only looked at.</summary>
public static IReadOnlyList<string> 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;
/// <summary>True when the folder holds one of the 4K Stogram database files (only their existence is checked).</summary>
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(@"^(?<y>\d{4})-(?<mo>\d{2})-(?<d>\d{2}) (?<h>\d{2})\.(?<mi>\d{2})\.(?<s>\d{2}) (?<content>\d{5,})_(?<user>\d{3,})$", RegexOptions.CultureInvariant)]
private static partial Regex StogramName();
}
+179
View File
@@ -0,0 +1,179 @@
using System.Diagnostics;
using System.Globalization;
using System.Text.Json;
namespace Febe.Core.Import;
/// <summary>Metadata of a video read by an external tool.</summary>
public sealed record VideoMetadata(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height);
/// <summary>
/// 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»).
/// </summary>
public interface IVideoMetadataProbe
{
/// <summary>Metadata of a video file, read-only; null when the tool cannot read it.</summary>
Task<VideoMetadata?> ProbeAsync(string path, CancellationToken ct = default);
}
/// <summary>
/// <see cref="IVideoMetadataProbe"/> with ffprobe, when installed (in Docker it comes with ffmpeg, §11). The output is
/// parsed with <see cref="JsonDocument"/>; error output is never logged (it may contain paths).
/// </summary>
public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe
{
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(20);
private FfprobeVideoMetadataProbe(string executable) => Executable = executable;
/// <summary>Full path of ffprobe.</summary>
public string Executable { get; }
/// <summary>Finds ffprobe on the PATH (or at <paramref name="explicitPath"/>); null when it is not available.</summary>
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<VideoMetadata?> 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;
}
/// <summary>Parses the JSON printed by ffprobe.</summary>
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.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.GetString(), 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 (JsonException)
{
return null;
}
}
private static DateTimeOffset? CreationTime(JsonElement element)
{
if (element.TryGetProperty("tags", out var tags) && tags.TryGetProperty("creation_time", out var value)
&& DateTimeOffset.TryParse(value.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var instant)
&& instant.Year >= 1995)
{
return instant.ToUniversalTime();
}
return null;
}
}
+46 -3
View File
@@ -17,6 +17,37 @@ public sealed record MediaContent
/// <summary>Drop the file beyond this size («Salta i video oltre», spec §4.4).</summary>
public long? MaxBytes { get; init; }
/// <summary>
/// Path relative to the account folder ('/' separated) to use instead of the naming scheme: imported files without
/// a known date and code go to <c>importati/</c> with their original name (spec §9.4). A taken name still becomes
/// «nome (2).ext»: nothing is overwritten.
/// </summary>
public string? FixedRelativePath { get; init; }
/// <summary>
/// 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 <see cref="ContentChangedException"/> is thrown.
/// </summary>
public string? ExpectedSha256 { get; init; }
}
/// <summary>The content read differs from <see cref="MediaContent.ExpectedSha256"/>: nothing was kept.</summary>
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
+64
View File
@@ -42,8 +42,72 @@ public interface IImportStore
/// <summary>Associates every file of a source folder with an account (null: not associated).</summary>
Task SetFolderTargetAsync(long runId, string folder, long? accountId, CancellationToken ct = default);
/// <summary>Source folders with their counts by outcome and their association (review table, mockup 09).</summary>
Task<IReadOnlyList<ImportFolderCounts>> ListFolderCountsAsync(long runId, CancellationToken ct = default);
/// <summary>
/// Probable-duplicate pairs of an import (the candidate side is always a file of the import), in creation order.
/// </summary>
Task<IReadOnlyList<DuplicatePair>> ListPairsAsync(long runId, bool pendingOnly, long afterId = 0, int limit = 500, CancellationToken ct = default);
Task<int> CountPairsAsync(long runId, bool pendingOnly, CancellationToken ct = default);
/// <summary>
/// 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.
/// </summary>
Task<IReadOnlyList<ImportReportRow>> ListReportRowsAsync(long runId, long afterId = 0, int limit = 1000, CancellationToken ct = default);
/// <summary>Removes the pairs of an import still waiting for a decision (the import was cancelled). Returns how many.</summary>
Task<int> RemovePendingPairsAsync(long runId, CancellationToken ct = default);
/// <summary>Removes an import with its files and pairs. Only records: no file on disk is touched.</summary>
Task DeleteRunAsync(long runId, CancellationToken ct = default);
/// <summary>
/// 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).
/// </summary>
Task<LibraryIdentifiers> LoadLibraryIdentifiersAsync(CancellationToken ct = default);
/// <summary>The entry of (account, kind) with this post code, in any state: imported posts known only by their code.</summary>
Task<Entry?> FindEntryByCodeAsync(long accountId, EntryKind kind, string code, CancellationToken ct = default);
}
/// <summary>A source folder of an import with its counts by outcome.</summary>
/// <param name="Folder">Folder relative to the source ('/' separated, empty for the root).</param>
/// <param name="Files">Files of the folder.</param>
/// <param name="Bytes">Their total size.</param>
/// <param name="ProbableAccount">Account guessed from the folder name.</param>
/// <param name="TargetAccountId">Associated account, when chosen.</param>
/// <param name="ByOutcome">Files per outcome (every outcome present, zero included).</param>
/// <param name="Recognized">Files whose Instagram identifier or code is known.</param>
public sealed record ImportFolderCounts(
string Folder,
int Files,
long Bytes,
string? ProbableAccount,
long? TargetAccountId,
IReadOnlyDictionary<ImportOutcome, int> ByOutcome,
int Recognized);
/// <summary>A file of an import for the report, with what it matched and where it went.</summary>
/// <param name="File">The file.</param>
/// <param name="MatchedUsername">Account of the library file it matched («Già in libreria», «Doppione probabile»).</param>
/// <param name="MatchedPath">Path of that library file, relative to its account folder.</param>
/// <param name="TargetUsername">User name of the destination account.</param>
public sealed record ImportReportRow(ImportFile File, string? MatchedUsername, string? MatchedPath, string? TargetUsername);
/// <summary>Identity of an entry of the library: Instagram identifier and post code.</summary>
public sealed record EntryIdentity(long EntryId, long AccountId, EntryKind Kind, EntryState State, string? InstagramId, string? Code);
/// <summary>A file of the library with its own Instagram identifier (an item of a series).</summary>
public sealed record MediaIdentity(long MediaId, long EntryId, string InstagramId);
/// <summary>Identifiers of the whole library.</summary>
public sealed record LibraryIdentifiers(IReadOnlyList<EntryIdentity> Entries, IReadOnlyList<MediaIdentity> Media);
/// <summary>Filters for the files of an import.</summary>
public sealed record ImportFileQuery
{