using System.Security.Cryptography;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Library;
/// Options of «Ricostruisci il database dalla libreria».
public sealed record RebuildOptions
{
///
/// Account folders outside the library to include (accounts whose folder was moved elsewhere, spec §4.4): after the
/// loss of the database Febe cannot know them by itself.
///
public IReadOnlyList ExtraAccountFolders { get; init; } = [];
/// Create missing thumbnails (photos; videos with ffmpeg when available).
public bool CreateThumbnails { get; init; } = true;
/// Files hashed in parallel.
public int Parallelism { get; init; } = Math.Max(1, Environment.ProcessorCount);
}
/// Progress of a rebuild.
public sealed record RebuildProgress(string Folder, int FoldersDone, int FoldersTotal, int FilesChecked);
/// What a rebuild found and did.
public sealed record RebuildReport
{
public int AccountFolders { get; init; }
/// Folders of the library without _febe.jsonl: not rebuilt (their files can be imported).
public IReadOnlyList FoldersWithoutJournal { get; init; } = [];
public int AccountsCreated { get; init; }
public int AccountsMatched { get; init; }
public int EntriesCreated { get; init; }
/// Entries already in the database (a rebuild over an existing database only adds what is missing).
public int EntriesAlreadyPresent { get; init; }
/// Remembered deletions restored as «eliminato»: those entries are not downloaded again.
public int EntriesDeleted { get; init; }
public int FilesVerified { get; init; }
public int FilesMissing { get; init; }
/// Files whose SHA-256 differs from the journal (the file on disk wins).
public int HashMismatches { get; init; }
/// Files in account folders that no journal line mentions: left untouched, not added.
public int UntrackedFiles { get; init; }
public int InvalidLines { get; init; }
/// A few examples of what needs attention (Italian), for the report screen.
public IReadOnlyList Notes { get; init; } = [];
}
///
/// «Ricostruisci il database dalla libreria» (spec §8.5): reads every account folder and its _febe.jsonl,
/// recomputes SHA-256 and perceptual hashes of the files on disk, honours deletions, and fills the database. Enough to
/// start again after losing the database without downloading anything again.
///
/// Idempotent: entries already present are left as they are, so it can also run on an existing database. It never
/// moves, renames or deletes a file (rule 12). Restored accounts are «In pausa»: Alberto resumes them.
///
///
public sealed class LibraryRebuilder(
IFebeStorage storage,
LibraryLayout layout,
IClock clock,
ThumbnailStore? thumbnails = null,
VideoFrameExtractor? frames = null,
PerceptualHashIndex? hashIndex = null)
{
private const int BatchSize = 200;
private const int MaxNotes = 50;
public async Task RebuildAsync(RebuildOptions? options = null, IProgress? progress = null, CancellationToken ct = default)
{
options ??= new RebuildOptions();
var report = new Accumulator();
var folders = new List();
if (Directory.Exists(layout.Root))
{
foreach (var directory in Directory.EnumerateDirectories(layout.Root).Order(StringComparer.Ordinal))
{
if (File.Exists(AccountJournal.PathFor(directory)))
{
folders.Add(directory);
}
else if (Directory.EnumerateFileSystemEntries(directory).Any())
{
report.FoldersWithoutJournal.Add(Path.GetFileName(directory));
}
}
}
foreach (var extra in options.ExtraAccountFolders)
{
var full = Path.GetFullPath(extra);
if (File.Exists(AccountJournal.PathFor(full)) && !folders.Contains(full))
{
folders.Add(full);
}
}
for (var i = 0; i < folders.Count; i++)
{
ct.ThrowIfCancellationRequested();
await RebuildFolderAsync(folders[i], options, report, ct).ConfigureAwait(false);
progress?.Report(new RebuildProgress(folders[i], i + 1, folders.Count, report.FilesVerified + report.FilesMissing));
}
report.AccountFolders = folders.Count;
return report.ToReport();
}
private async Task RebuildFolderAsync(string folder, RebuildOptions options, Accumulator report, CancellationToken ct)
{
var journal = await AccountJournal.ReadAsync(folder, ct).ConfigureAwait(false);
report.InvalidLines += journal.InvalidLines;
if (journal.Lines.Count == 0)
{
report.Note($"«{Path.GetFileName(folder)}»: _febe.jsonl non contiene righe leggibili.");
return;
}
var account = await ResolveAccountAsync(folder, journal.Lines, report, ct).ConfigureAwait(false);
var allItems = Fold(journal.Lines, report);
// Entries already in the database are left as they are (deletions excepted): no hashing, no change.
var items = await SplitPresentAsync(account, allItems, report, ct).ConfigureAwait(false);
// Verify files in parallel: hashing dominates the time.
var live = items.Where(i => !i.Deleted).ToList();
var files = live.SelectMany(i => i.Files.Values.Select(f => (Item: i, File: f))).ToList();
var checks = new Dictionary<(Item, int), FileCheck>();
var gate = new Lock();
await Parallel.ForEachAsync(
files,
new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, options.Parallelism), CancellationToken = ct },
async (pair, token) =>
{
var check = await CheckFileAsync(folder, pair.File, options.CreateThumbnails, token).ConfigureAwait(false);
lock (gate)
{
checks[(pair.Item, pair.File.N)] = check;
}
}).ConfigureAwait(false);
var batch = new List<(Item Item, NewEntry Entry)>();
foreach (var item in items)
{
ct.ThrowIfCancellationRequested();
var entry = BuildEntry(account.Id, item);
var media = item.Files.Values.OrderBy(f => f.N).Select(f => BuildMedia(item, f, item.Deleted ? null : checks[(item, f.N)], report)).ToList();
batch.Add((item, new NewEntry(entry, media)));
if (batch.Count >= BatchSize)
{
await FlushAsync(account, batch, report, ct).ConfigureAwait(false);
}
}
await FlushAsync(account, batch, report, ct).ConfigureAwait(false);
CountUntracked(folder, allItems, report);
}
///
/// Returns the items that are not in the database yet. Items already present are counted; a remembered deletion
/// is applied to them if the database still shows them.
///
private async Task> SplitPresentAsync(Account account, List- items, Accumulator report, CancellationToken ct)
{
var paths = await storage.Media.MapPathsAsync(account.Id, ct).ConfigureAwait(false);
var known = new HashSet<(EntryKind, string)>();
foreach (var group in items.Where(i => i.InstagramId is not null).GroupBy(i => i.Kind))
{
var ids = await storage.Entries.GetKnownInstagramIdsAsync(account.Id, group.Key, group.Select(i => i.InstagramId!).ToList(), ct).ConfigureAwait(false);
foreach (var id in ids)
{
known.Add((group.Key, id));
}
}
var missing = new List
- ();
foreach (var item in items)
{
var present = item.InstagramId is { } id
? known.Contains((item.Kind, id))
: item.Files.Values.Any(f => paths.ContainsKey(LibraryLayout.ToStored(f.Path)));
if (!present)
{
missing.Add(item);
continue;
}
report.EntriesAlreadyPresent++;
if (item.Deleted)
{
report.EntriesDeleted++;
var existing = item.InstagramId is { } existingId
? await storage.Entries.FindAsync(account.Id, item.Kind, existingId, ct).ConfigureAwait(false)
: null;
if (existing is not null && existing.State != EntryState.Deleted)
{
await storage.Entries.MarkDeletedAsync(existing.Id, item.DeletedAt ?? clock.Now, ct).ConfigureAwait(false);
}
}
}
return missing;
}
private async Task ResolveAccountAsync(string folder, IReadOnlyList lines, Accumulator report, CancellationToken ct)
{
var last = lines[^1].Account;
var instagramId = lines.Select(l => l.Account.Id).LastOrDefault(id => !string.IsNullOrWhiteSpace(id));
var displayName = lines.Select(l => l.Account.DisplayName).LastOrDefault(n => !string.IsNullOrWhiteSpace(n));
var isMine = lines.Any(l => l.Account.IsMine == true);
Account? account = null;
if (instagramId is not null)
{
account = await storage.Accounts.FindByInstagramIdAsync(instagramId, ct).ConfigureAwait(false);
}
account ??= await storage.Accounts.FindByUsernameAsync(last.Username, ct).ConfigureAwait(false);
if (account is not null)
{
report.AccountsMatched++;
return account;
}
if (isMine && await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false) is not null)
{
isMine = false;
}
var now = clock.Now;
var created = Account.Create(last.Username, StartingPoint.EverythingAndKeepUpdated, now, clock.LocalZone, isMine: isMine) with
{
InstagramId = instagramId,
DisplayName = displayName,
State = AccountState.Paused,
StateChangedAt = now,
Folder = layout.FolderSetting(folder, last.Username),
};
report.AccountsCreated++;
report.Note($"Account @{last.Username} ripristinato «In pausa»: riattivalo dalla pagina Account.");
return await storage.Accounts.AddAsync(created, ct).ConfigureAwait(false);
}
/// Replays the journal: the last save of an entry wins, deletions remove it or mark it.
private static List
- Fold(IReadOnlyList lines, Accumulator report)
{
var order = new List
- ();
var byKey = new Dictionary(StringComparer.Ordinal);
foreach (var line in lines)
{
if (line.Kind is not { } kind)
{
report.InvalidLines++;
continue;
}
var key = KeyOf(kind, line);
byKey.TryGetValue(key, out var item);
if (line.Op == JournalOps.Save)
{
if (item is null || item.Deleted)
{
if (item is not null)
{
order.Remove(item);
}
item = new Item(kind, line);
byKey[key] = item;
order.Add(item);
}
else
{
item.Last = line;
}
foreach (var file in line.Files ?? [])
{
item.Files[file.N] = file;
}
}
else if (line.Remember == true)
{
if (item is null)
{
item = new Item(kind, line);
byKey[key] = item;
order.Add(item);
}
item.Deleted = true;
item.DeletedAt = line.At;
}
else if (item is not null)
{
order.Remove(item);
byKey.Remove(key);
}
}
return order;
}
private static string KeyOf(EntryKind kind, JournalLine line)
{
if (!string.IsNullOrWhiteSpace(line.Entry.Id))
{
return $"{kind}|id|{line.Entry.Id.Trim()}";
}
var firstPath = line.Files?.OrderBy(f => f.N).FirstOrDefault()?.Path;
return firstPath is not null
? $"{kind}|path|{firstPath}"
: $"{kind}|time|{line.Entry.PublishedAt.ToUnixTimeMilliseconds()}";
}
private async Task CheckFileAsync(string folder, JournalFile file, bool createThumbnails, CancellationToken ct)
{
string path;
try
{
path = LibraryLayout.FullPath(folder, file.Path);
}
catch (ArgumentException)
{
return FileCheck.Missing;
}
if (!File.Exists(path))
{
return FileCheck.Missing;
}
string sha;
long bytes;
await using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan))
{
bytes = stream.Length;
sha = Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
}
var isVideo = string.Equals(file.Type, "video", StringComparison.OrdinalIgnoreCase);
ulong? phash = null;
int? width = file.Width, height = file.Height;
var thumbnail = thumbnails?.Exists(sha) ?? false;
if (!isVideo)
{
phash = PerceptualHash.ComputeFromFile(path);
await using (var stream = File.OpenRead(path))
{
if (ImageDecoding.ReadSize(stream) is { } size)
{
(width, height) = size;
}
}
if (createThumbnails && thumbnails is not null && !thumbnail)
{
thumbnail = thumbnails.CreateFromFile(sha, path);
}
}
else if (createThumbnails && thumbnails is not null && !thumbnail && frames is not null)
{
var frame = await frames.ExtractJpegAsync(path, ct).ConfigureAwait(false);
if (frame is not null)
{
using var stream = new MemoryStream(frame);
thumbnail = thumbnails.Create(sha, stream);
}
}
return new FileCheck(true, bytes, sha, phash, width, height, thumbnail);
}
private static Entry BuildEntry(long accountId, Item item)
{
var e = item.Last.Entry;
var imported = string.Equals(e.Provenance, "imported", StringComparison.OrdinalIgnoreCase);
return new Entry
{
AccountId = accountId,
Kind = item.Kind,
InstagramId = string.IsNullOrWhiteSpace(e.Id) ? null : e.Id.Trim(),
Code = e.Code,
PublishedAt = e.PublishedAt,
Caption = e.Caption,
AuthorUsername = e.Author,
AuthorInstagramId = e.AuthorId,
Provenance = imported ? Provenance.Imported : Provenance.Downloaded,
State = item.Deleted ? EntryState.Deleted : EntryState.ToDownload, // recomputed from the files
DiscoveredAt = item.First.At,
DownloadedAt = item.Deleted ? null : item.Last.At,
DeletedAt = item.Deleted ? item.DeletedAt : null,
ExpiresAt = e.ExpiresAt,
};
}
private static Media BuildMedia(Item item, JournalFile file, FileCheck? check, Accumulator report)
{
var kind = string.Equals(file.Type, "video", StringComparison.OrdinalIgnoreCase) ? MediaKind.Video : MediaKind.Photo;
var media = new Media
{
Position = file.N,
Kind = kind,
InstagramId = file.Id,
Width = file.Width,
Height = file.Height,
Duration = file.DurationMs is { } ms ? TimeSpan.FromMilliseconds(ms) : null,
Sha256 = file.Sha256 is { Length: 64 } s ? s.ToLowerInvariant() : null,
Bytes = file.Bytes,
};
if (item.Deleted)
{
return media with { State = MediaState.Deleted };
}
if (check is not { Exists: true })
{
report.FilesMissing++;
report.Note($"File mancante: {file.Path}");
return media with { State = MediaState.Failed, LastError = "File non trovato durante la ricostruzione del database." };
}
report.FilesVerified++;
if (media.Sha256 is not null && !string.Equals(media.Sha256, check.Sha256, StringComparison.Ordinal))
{
report.HashMismatches++;
report.Note($"Contenuto diverso da quello registrato: {file.Path}");
}
var imported = string.Equals(item.Last.Entry.Provenance, "imported", StringComparison.OrdinalIgnoreCase);
return media with
{
State = imported ? MediaState.Imported : MediaState.Downloaded,
RelativePath = LibraryLayout.ToStored(file.Path),
Bytes = check.Bytes,
Sha256 = check.Sha256,
PerceptualHash = check.PerceptualHash,
Width = check.Width ?? media.Width,
Height = check.Height ?? media.Height,
HasThumbnail = check.HasThumbnail,
DownloadedAt = item.Last.At,
};
}
private async Task FlushAsync(Account account, List<(Item Item, NewEntry Entry)> batch, Accumulator report, CancellationToken ct)
{
if (batch.Count == 0)
{
return;
}
var results = await storage.Entries.AddManyAsync(batch.Select(b => b.Entry).ToList(), ct).ConfigureAwait(false);
for (var i = 0; i < results.Count; i++)
{
var (item, _) = batch[i];
var result = results[i];
var stored = result.Stored;
if (result.Created)
{
report.EntriesCreated++;
}
else
{
report.EntriesAlreadyPresent++;
if (item.Deleted && stored.Entry.State != EntryState.Deleted)
{
await storage.Entries.MarkDeletedAsync(stored.Entry.Id, item.DeletedAt ?? clock.Now, ct).ConfigureAwait(false);
}
}
if (item.Deleted)
{
report.EntriesDeleted++;
continue;
}
if (result.Created && hashIndex is not null)
{
foreach (var media in stored.Media)
{
if (media.PerceptualHash is { } hash && EntryStateRules.IsPresent(media.State))
{
hashIndex.Add(media.Id, account.Id, hash);
}
}
}
foreach (var highlight in item.Last.Entry.Highlights ?? [])
{
var collection = !string.IsNullOrWhiteSpace(highlight.Id)
? await storage.Highlights.FindAsync(account.Id, highlight.Id, ct).ConfigureAwait(false)
: await storage.Highlights.FindByTitleAsync(account.Id, highlight.Title, ct).ConfigureAwait(false);
collection ??= await storage.Highlights.UpsertAsync(
new Highlight
{
AccountId = account.Id,
InstagramId = highlight.Id,
Title = highlight.Title,
Position = highlight.Position ?? 0,
DiscoveredAt = item.First.At,
},
ct).ConfigureAwait(false);
await storage.Highlights.AddItemAsync(collection.Id, stored.Entry.Id, ct).ConfigureAwait(false);
}
}
batch.Clear();
}
private static void CountUntracked(string folder, List
- items, Accumulator report)
{
var known = new HashSet(
items.SelectMany(i => i.Files.Values).Select(f => LibraryLayout.ToStored(f.Path)),
OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
foreach (var file in Directory.EnumerateFiles(folder, "*", new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true }))
{
var name = Path.GetFileName(file);
if (name == AccountJournal.FileName || SafeFileWriter.IsTemporaryFile(file))
{
continue;
}
var relative = LibraryLayout.ToStored(Path.GetRelativePath(folder, file));
if (!known.Contains(relative))
{
report.UntrackedFiles++;
report.Note($"File non registrato in _febe.jsonl (lasciato dov'è): {Path.GetFileName(folder)}/{relative}");
}
}
}
private sealed record FileCheck(bool Exists, long Bytes, string Sha256, ulong? PerceptualHash, int? Width, int? Height, bool HasThumbnail)
{
public static FileCheck Missing { get; } = new(false, 0, string.Empty, null, null, null, false);
}
private sealed class Item(EntryKind kind, JournalLine first)
{
public EntryKind Kind { get; } = kind;
public JournalLine First { get; } = first;
public JournalLine Last { get; set; } = first;
public string? InstagramId => string.IsNullOrWhiteSpace(Last.Entry.Id) ? null : Last.Entry.Id.Trim();
public SortedDictionary Files { get; } = [];
public bool Deleted { get; set; }
public DateTimeOffset? DeletedAt { get; set; }
}
private sealed class Accumulator
{
private readonly List _notes = [];
public int AccountFolders { get; set; }
public List FoldersWithoutJournal { get; } = [];
public int AccountsCreated { get; set; }
public int AccountsMatched { get; set; }
public int EntriesCreated { get; set; }
public int EntriesAlreadyPresent { get; set; }
public int EntriesDeleted { get; set; }
public int FilesVerified { get; set; }
public int FilesMissing { get; set; }
public int HashMismatches { get; set; }
public int UntrackedFiles { get; set; }
public int InvalidLines { get; set; }
public void Note(string note)
{
if (_notes.Count < MaxNotes)
{
_notes.Add(note);
}
}
public RebuildReport ToReport() => new()
{
AccountFolders = AccountFolders,
FoldersWithoutJournal = FoldersWithoutJournal,
AccountsCreated = AccountsCreated,
AccountsMatched = AccountsMatched,
EntriesCreated = EntriesCreated,
EntriesAlreadyPresent = EntriesAlreadyPresent,
EntriesDeleted = EntriesDeleted,
FilesVerified = FilesVerified,
FilesMissing = FilesMissing,
HashMismatches = HashMismatches,
UntrackedFiles = UntrackedFiles,
InvalidLines = InvalidLines,
Notes = _notes,
};
}
}