From 3aeaa17da7f70cd04129d993b026cbb07d15ba5f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 13 Oct 2026 16:06:15 +0000 Subject: [PATCH] M1 Dati e libreria: modello, archivi SQLite con scrittore unico, nomi dei file, scrittura sicura, miniature, impronte, _febe.jsonl, copie, eliminazione e ricostruzione Modello del dominio e interfacce degli archivi in Febe.Core; implementazione SQLite in Febe.Data (WAL, chiavi esterne, migrazioni numerate in transazione, coda di scrittura su un solo thread); logica della libreria in Febe.Core/Library; 164 prove MSTest, compresa la ricostruzione del database da una libreria di prova e la scala a 200.000 elementi. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA --- src/Febe.Core/Domain/Account.cs | 216 ++++++ src/Febe.Core/Domain/DuplicatePair.cs | 67 ++ src/Febe.Core/Domain/EngineRecords.cs | 211 ++++++ src/Febe.Core/Domain/Entry.cs | 137 ++++ src/Febe.Core/Domain/Highlight.cs | 33 + src/Febe.Core/Domain/Import.cs | 181 +++++ src/Febe.Core/Domain/LocalCalendar.cs | 59 ++ src/Febe.Core/Domain/Media.cs | 98 +++ src/Febe.Core/Library/AccountJournal.cs | 293 ++++++++ src/Febe.Core/Library/DailyBackup.cs | 123 ++++ src/Febe.Core/Library/DataFolderCheck.cs | 328 +++++++++ src/Febe.Core/Library/ImageDecoding.cs | 131 ++++ src/Febe.Core/Library/LibraryDeletion.cs | 146 ++++ src/Febe.Core/Library/LibraryIngest.cs | 220 ++++++ src/Febe.Core/Library/LibraryLayout.cs | 133 ++++ src/Febe.Core/Library/LibraryRebuilder.cs | 623 +++++++++++++++++ src/Febe.Core/Library/LibrarySettings.cs | 44 ++ src/Febe.Core/Library/NamingPreview.cs | 78 +++ src/Febe.Core/Library/NamingScheme.cs | 282 ++++++++ src/Febe.Core/Library/PerceptualHash.cs | 235 +++++++ src/Febe.Core/Library/PerceptualHashIndex.cs | 164 +++++ src/Febe.Core/Library/SafeFileWriter.cs | 292 ++++++++ src/Febe.Core/Library/TextSearch.cs | 61 ++ src/Febe.Core/Library/ThumbnailStore.cs | 176 +++++ src/Febe.Core/Library/VideoFrameExtractor.cs | 120 ++++ src/Febe.Core/Library/WindowsFileNames.cs | 185 +++++ src/Febe.Core/Storage/IAccountStore.cs | 99 +++ src/Febe.Core/Storage/IDuplicateStore.cs | 22 + src/Febe.Core/Storage/IEngineStores.cs | 163 +++++ src/Febe.Core/Storage/IEntryStore.cs | 76 +++ src/Febe.Core/Storage/IFebeStorage.cs | 58 ++ src/Febe.Core/Storage/IHighlightStore.cs | 41 ++ src/Febe.Core/Storage/IImportStore.cs | 71 ++ src/Febe.Core/Storage/IMediaStore.cs | 52 ++ src/Febe.Core/Storage/ISettingsStore.cs | 63 ++ src/Febe.Core/Storage/LibraryQueries.cs | 181 +++++ src/Febe.Data/FebeDatabase.cs | 230 +++++++ src/Febe.Data/MigrationRunner.cs | 138 ++++ src/Febe.Data/Migrations/0001_schema.sql | 291 ++++++++ src/Febe.Data/Sql.cs | 123 ++++ src/Febe.Data/SqliteWriter.cs | 324 +++++++++ src/Febe.Data/Stores/AccountStore.cs | 459 +++++++++++++ src/Febe.Data/Stores/DuplicateStore.cs | 111 +++ src/Febe.Data/Stores/EngineStores.cs | 635 ++++++++++++++++++ src/Febe.Data/Stores/EntryMapping.cs | 191 ++++++ src/Febe.Data/Stores/EntryStore.cs | 521 ++++++++++++++ src/Febe.Data/Stores/HighlightStore.cs | 195 ++++++ src/Febe.Data/Stores/ImportStore.cs | 311 +++++++++ src/Febe.Data/Stores/MediaStore.cs | 228 +++++++ tests/Febe.Tests/Data/AccountStoreTests.cs | 161 +++++ tests/Febe.Tests/Data/ConstraintTests.cs | 148 ++++ tests/Febe.Tests/Data/EngineStoreTests.cs | 326 +++++++++ tests/Febe.Tests/Data/EntryStoreTests.cs | 300 +++++++++ tests/Febe.Tests/Data/LibraryScaleTests.cs | 131 ++++ tests/Febe.Tests/Data/MigrationTests.cs | 161 +++++ tests/Febe.Tests/Data/SingleWriterTests.cs | 144 ++++ .../Febe.Tests/Library/AccountJournalTests.cs | 116 ++++ tests/Febe.Tests/Library/DailyBackupTests.cs | 96 +++ .../Library/DataFolderCheckTests.cs | 137 ++++ .../Library/LibraryDeletionTests.cs | 102 +++ .../Febe.Tests/Library/LibraryIngestTests.cs | 120 ++++ .../Febe.Tests/Library/LibraryRebuildTests.cs | 175 +++++ tests/Febe.Tests/Library/NamingSchemeTests.cs | 166 +++++ .../Febe.Tests/Library/PerceptualHashTests.cs | 187 ++++++ .../Febe.Tests/Library/SafeFileWriterTests.cs | 167 +++++ .../Febe.Tests/Library/ThumbnailStoreTests.cs | 143 ++++ .../Library/WindowsFileNamesTests.cs | 124 ++++ .../Febe.Tests/Support/LibraryTestSupport.cs | 253 +++++++ tests/Febe.Tests/Support/TestLibrary.cs | 96 +++ 69 files changed, 12472 insertions(+) create mode 100644 src/Febe.Core/Domain/Account.cs create mode 100644 src/Febe.Core/Domain/DuplicatePair.cs create mode 100644 src/Febe.Core/Domain/EngineRecords.cs create mode 100644 src/Febe.Core/Domain/Entry.cs create mode 100644 src/Febe.Core/Domain/Highlight.cs create mode 100644 src/Febe.Core/Domain/Import.cs create mode 100644 src/Febe.Core/Domain/LocalCalendar.cs create mode 100644 src/Febe.Core/Domain/Media.cs create mode 100644 src/Febe.Core/Library/AccountJournal.cs create mode 100644 src/Febe.Core/Library/DailyBackup.cs create mode 100644 src/Febe.Core/Library/DataFolderCheck.cs create mode 100644 src/Febe.Core/Library/ImageDecoding.cs create mode 100644 src/Febe.Core/Library/LibraryDeletion.cs create mode 100644 src/Febe.Core/Library/LibraryIngest.cs create mode 100644 src/Febe.Core/Library/LibraryLayout.cs create mode 100644 src/Febe.Core/Library/LibraryRebuilder.cs create mode 100644 src/Febe.Core/Library/LibrarySettings.cs create mode 100644 src/Febe.Core/Library/NamingPreview.cs create mode 100644 src/Febe.Core/Library/NamingScheme.cs create mode 100644 src/Febe.Core/Library/PerceptualHash.cs create mode 100644 src/Febe.Core/Library/PerceptualHashIndex.cs create mode 100644 src/Febe.Core/Library/SafeFileWriter.cs create mode 100644 src/Febe.Core/Library/TextSearch.cs create mode 100644 src/Febe.Core/Library/ThumbnailStore.cs create mode 100644 src/Febe.Core/Library/VideoFrameExtractor.cs create mode 100644 src/Febe.Core/Library/WindowsFileNames.cs create mode 100644 src/Febe.Core/Storage/IAccountStore.cs create mode 100644 src/Febe.Core/Storage/IDuplicateStore.cs create mode 100644 src/Febe.Core/Storage/IEngineStores.cs create mode 100644 src/Febe.Core/Storage/IEntryStore.cs create mode 100644 src/Febe.Core/Storage/IFebeStorage.cs create mode 100644 src/Febe.Core/Storage/IHighlightStore.cs create mode 100644 src/Febe.Core/Storage/IImportStore.cs create mode 100644 src/Febe.Core/Storage/IMediaStore.cs create mode 100644 src/Febe.Core/Storage/ISettingsStore.cs create mode 100644 src/Febe.Core/Storage/LibraryQueries.cs create mode 100644 src/Febe.Data/FebeDatabase.cs create mode 100644 src/Febe.Data/MigrationRunner.cs create mode 100644 src/Febe.Data/Migrations/0001_schema.sql create mode 100644 src/Febe.Data/Sql.cs create mode 100644 src/Febe.Data/SqliteWriter.cs create mode 100644 src/Febe.Data/Stores/AccountStore.cs create mode 100644 src/Febe.Data/Stores/DuplicateStore.cs create mode 100644 src/Febe.Data/Stores/EngineStores.cs create mode 100644 src/Febe.Data/Stores/EntryMapping.cs create mode 100644 src/Febe.Data/Stores/EntryStore.cs create mode 100644 src/Febe.Data/Stores/HighlightStore.cs create mode 100644 src/Febe.Data/Stores/ImportStore.cs create mode 100644 src/Febe.Data/Stores/MediaStore.cs create mode 100644 tests/Febe.Tests/Data/AccountStoreTests.cs create mode 100644 tests/Febe.Tests/Data/ConstraintTests.cs create mode 100644 tests/Febe.Tests/Data/EngineStoreTests.cs create mode 100644 tests/Febe.Tests/Data/EntryStoreTests.cs create mode 100644 tests/Febe.Tests/Data/LibraryScaleTests.cs create mode 100644 tests/Febe.Tests/Data/MigrationTests.cs create mode 100644 tests/Febe.Tests/Data/SingleWriterTests.cs create mode 100644 tests/Febe.Tests/Library/AccountJournalTests.cs create mode 100644 tests/Febe.Tests/Library/DailyBackupTests.cs create mode 100644 tests/Febe.Tests/Library/DataFolderCheckTests.cs create mode 100644 tests/Febe.Tests/Library/LibraryDeletionTests.cs create mode 100644 tests/Febe.Tests/Library/LibraryIngestTests.cs create mode 100644 tests/Febe.Tests/Library/LibraryRebuildTests.cs create mode 100644 tests/Febe.Tests/Library/NamingSchemeTests.cs create mode 100644 tests/Febe.Tests/Library/PerceptualHashTests.cs create mode 100644 tests/Febe.Tests/Library/SafeFileWriterTests.cs create mode 100644 tests/Febe.Tests/Library/ThumbnailStoreTests.cs create mode 100644 tests/Febe.Tests/Library/WindowsFileNamesTests.cs create mode 100644 tests/Febe.Tests/Support/LibraryTestSupport.cs create mode 100644 tests/Febe.Tests/Support/TestLibrary.cs diff --git a/src/Febe.Core/Domain/Account.cs b/src/Febe.Core/Domain/Account.cs new file mode 100644 index 0000000..065f590 --- /dev/null +++ b/src/Febe.Core/Domain/Account.cs @@ -0,0 +1,216 @@ +namespace Febe.Core.Domain; + +/// «Quanto indietro nel tempo» (spec §4.4). +public enum HistoryDepth +{ + /// Tutto: the whole history. + All, + + /// Ultimi N post: only the most recent posts. + LastPosts, + + /// Da una data: only content published from onward. + FromDate, +} + +/// Why an account is «Non raggiungibile» (spec §4.2). +public enum UnreachableReason +{ + /// Private profile that Alberto does not follow: never touched (rule 6). + PrivateNotFollowed, + + /// The profile does not exist (any more). + NotFound, + + /// The profile blocked Alberto or is restricted. + Blocked, + + /// A profile that is not followed changed name: Alberto must indicate the new one. + Renamed, +} + +/// +/// Notices that put an account in the «Da controllare» filter together with the Unreachable state (spec §4.2). +/// They stay until Alberto acknowledges them. +/// +[Flags] +public enum AccountNotices +{ + None = 0, + + /// The profile changed name: Febe updated it and kept the folder. + Renamed = 1, + + /// A reader met a response format it did not recognize (spec §6.4). + UnrecognizedFormat = 2, +} + +/// Per-account limits (spec §4.4 «Limiti»). Account and general limits apply together: the stricter wins. +public sealed record AccountLimits +{ + public HistoryDepth Depth { get; init; } = HistoryDepth.All; + + /// Number of most recent posts to keep when is . + public int? LastPosts { get; init; } + + /// First instant (UTC) of the period to download when is . + public DateTimeOffset? FromDate { get; init; } + + /// «Storico, massimo al giorno»: backfill posts per day for this account. + public int BackfillPostsPerDay { get; init; } = CautionProfile.Prudent.BackfillPostsPerAccountPerDay; + + /// Videos larger than this are skipped. Null means no limit (the default). + public long? MaxVideoBytes { get; init; } + + /// «Scarica anche i video delle storie». + public bool StoryVideos { get; init; } = true; +} + +/// +/// An Instagram account that Febe archives (spec §4.2, §4.4, §8.3). +/// +/// The identity of an account is its numeric Instagram identifier (), never the user name: +/// a renamed profile keeps its row, its entries and its folder. is the local row key used by the +/// database and by IGovernor; it exists because accounts created by the import («Solo archivio») may not know +/// their Instagram identifier yet. +/// +/// +public sealed record Account +{ + /// Local key (0 until stored). + public long Id { get; init; } + + /// Numeric Instagram identifier, as text. Unique when present; null only for archive-only accounts. + public string? InstagramId { get; init; } + + public required string Username { get; init; } + + public string? DisplayName { get; init; } + + public bool IsPrivate { get; init; } + + /// Alberto follows this profile. + public bool IsFollowed { get; init; } + + /// Alberto's own profile («Tu»). At most one account has it. + public bool IsMine { get; init; } + + public AccountState State { get; init; } = AccountState.UpToDate; + + /// When last changed (e.g. «Messo in pausa da te il 2 ottobre»). + public DateTimeOffset? StateChangedAt { get; init; } + + public UnreachableReason? UnreachableReason { get; init; } + + /// «Tieni aggiornato». With false a single download is made, then the account stays paused. + public bool KeepUpdated { get; init; } = true; + + public Frequency Frequency { get; init; } = Frequency.Normal; + + /// «Su misura»: how often to check posts. + public TimeSpan? CustomPostInterval { get; init; } + + /// «Su misura»: maximum interval between two story checks. + public TimeSpan? CustomStoryInterval { get; init; } + + /// «Cosa scaricare». + public ContentTypes ContentTypes { get; init; } = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Stories + | ContentTypes.Highlights | ContentTypes.ProfilePicture; + + public AccountLimits Limits { get; init; } = new(); + + /// + /// Folder of the account. Null means the default <Libreria>/<username>; a relative path is relative + /// to the library (a renamed account keeps its old folder this way); an absolute path may be outside the library. + /// Resolved by Febe.Core.Library.LibraryLayout.AccountFolder. + /// + public string? Folder { get; init; } + + /// Opaque resume point of the backfill (Storico), written by the collection pipeline. + public string? BackfillCursor { get; init; } + + /// When the backfill reached the limit or the oldest post. + public DateTimeOffset? BackfillCompletedAt { get; init; } + + /// Number of posts declared by the profile, when known (used to estimate the backfill). + public int? PostCount { get; init; } + + public DateTimeOffset? LastProfileCheckAt { get; init; } + + public DateTimeOffset? NextProfileCheckAt { get; init; } + + public DateTimeOffset? LastStoriesCheckAt { get; init; } + + public DateTimeOffset? NextStoriesCheckAt { get; init; } + + public AccountNotices Notices { get; init; } + + /// Last user name before a rename. + public string? PreviousUsername { get; init; } + + public DateTimeOffset? RenamedAt { get; init; } + + /// Last time a reader met an unknown format for this account. + public DateTimeOffset? FormatUnrecognizedAt { get; init; } + + public required DateTimeOffset AddedAt { get; init; } + + /// True for the «Da controllare» filter: unreachable, renamed or with an unrecognized format. + public bool NeedsAttention => State == AccountState.Unreachable || Notices != AccountNotices.None; + + /// + /// A new account with the values of a starting point (spec §4.2). Common values: frequency Normal, + /// tagged posts only for Alberto's own profile, backfill per day from the caution profile, no video size limit, + /// story videos included, default folder. + /// + /// User name. + /// One of the three starting points. + /// Current time (from IClock). + /// Alberto's time zone: «da oggi» starts at local midnight. + /// Caution profile in use (defaults to Prudente). + /// Alberto's own profile: «Post in cui è taggato» is on. + public static Account Create( + string username, + StartingPoint startingPoint, + DateTimeOffset now, + TimeZoneInfo zone, + CautionProfile? profile = null, + bool isMine = false) + { + ArgumentException.ThrowIfNullOrWhiteSpace(username); + ArgumentNullException.ThrowIfNull(zone); + profile ??= CautionProfile.Prudent; + + var everything = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Stories + | ContentTypes.Highlights | ContentTypes.ProfilePicture; + var types = startingPoint == StartingPoint.OnlyStories + ? ContentTypes.Stories | ContentTypes.Highlights + : everything; + if (isMine && startingPoint != StartingPoint.OnlyStories) + { + types |= ContentTypes.Tagged; + } + + var limits = new AccountLimits { BackfillPostsPerDay = profile.BackfillPostsPerAccountPerDay }; + if (startingPoint == StartingPoint.OnlyNewFromToday) + { + limits = limits with + { + Depth = HistoryDepth.FromDate, + FromDate = LocalCalendar.StartOfDay(LocalCalendar.Today(now, zone), zone), + }; + } + + return new Account + { + Username = username.Trim().TrimStart('@'), + IsMine = isMine, + KeepUpdated = true, + Frequency = Frequency.Normal, + ContentTypes = types, + Limits = limits, + AddedAt = now, + StateChangedAt = now, + }; + } +} diff --git a/src/Febe.Core/Domain/DuplicatePair.cs b/src/Febe.Core/Domain/DuplicatePair.cs new file mode 100644 index 0000000..1fc747d --- /dev/null +++ b/src/Febe.Core/Domain/DuplicatePair.cs @@ -0,0 +1,67 @@ +namespace Febe.Core.Domain; + +/// Where a probable duplicate was found. +public enum DuplicateOrigin +{ + /// A file just downloaded looks like one already in the library (spec §9.5). + Download, + + /// A file of an import looks like one in the library or in the same source (spec §9.3). + Import, +} + +/// Why two files are probable duplicates (spec §9.3). +public enum DuplicateReason +{ + /// Same Instagram identifier, different file. + SameInstagramId, + + /// Very close perceptual hashes. + VisuallySimilar, +} + +/// Alberto's decision on a probable duplicate. No choice is made in advance (mockup 09). +public enum DuplicateDecision +{ + Pending, + + /// «Tieni il più grande». If the larger is the new one it replaces a library file: an explicit choice (rule 12). + KeepLarger, + + /// «Tieni quello in libreria». + KeepExisting, + + /// «Tienili entrambi». + KeepBoth, +} + +/// +/// A pair of files that are probably the same content, waiting for Alberto's decision (spec §8.3 duplicate_pair). +/// Each side is either a library file (*MediaId) or a file of an import (*ImportFileId): exactly one per side. +/// The existing side is the library file (or, for duplicates inside a source, the first file met). +/// +public sealed record DuplicatePair +{ + public long Id { get; init; } + + public required DuplicateOrigin Origin { get; init; } + + public required DuplicateReason Reason { get; init; } + + public long? ExistingMediaId { get; init; } + + public long? ExistingImportFileId { get; init; } + + public long? CandidateMediaId { get; init; } + + public long? CandidateImportFileId { get; init; } + + /// Hamming distance of the perceptual hashes, when the reason is visual. + public int? Distance { get; init; } + + public DuplicateDecision Decision { get; init; } = DuplicateDecision.Pending; + + public required DateTimeOffset CreatedAt { get; init; } + + public DateTimeOffset? DecidedAt { get; init; } +} diff --git a/src/Febe.Core/Domain/EngineRecords.cs b/src/Febe.Core/Domain/EngineRecords.cs new file mode 100644 index 0000000..e153804 --- /dev/null +++ b/src/Febe.Core/Domain/EngineRecords.cs @@ -0,0 +1,211 @@ +using Febe.Core.Abstractions; + +namespace Febe.Core.Domain; + +/// What a queued engine task does: one recipe of spec §6.3 on one account (or none). +public enum EngineTaskKind +{ + /// Giro dei seguiti: home and stories bar. + FollowingSweep, + + /// Storie di un account. + AccountStories, + + /// Controllo del profilo. + ProfileCheck, + + /// Storico. + Backfill, + + /// Raccolta in evidenza. + HighlightCheck, + + /// Scheda Taggati. + TaggedCheck, + + /// Scheda Reel. + ReelsCheck, + + /// Post singolo (also to refresh an expired address). + SinglePost, + + /// Elenco dei seguiti, on request only. + FollowingList, +} + +public enum EngineTaskState +{ + Pending, + Running, + Done, + Failed, + Cancelled, +} + +/// A task of the engine queue (spec §8.3 task). Persisted so that a restart resets nothing. +public sealed record EngineTask +{ + public long Id { get; init; } + + public required EngineTaskKind Kind { get; init; } + + public long? AccountId { get; init; } + + /// Not before this instant. + public required DateTimeOffset DueAt { get; init; } + + /// Higher runs first among due tasks («Controlla ora» goes on top). + public int Priority { get; init; } + + public EngineTaskState State { get; init; } = EngineTaskState.Pending; + + /// Optional arguments (e.g. a post code), as compact text or JSON. Never secrets. + public string? Payload { get; init; } + + /// Asked by Alberto (spec §7.8). + public bool IsManual { get; init; } + + public int Attempts { get; init; } + + public required DateTimeOffset CreatedAt { get; init; } + + public DateTimeOffset? StartedAt { get; init; } + + public DateTimeOffset? CompletedAt { get; init; } + + public string? LastError { get; init; } +} + +/// +/// One counted action toward the site (spec §7.4 action_log): the basis of the budgets. For +/// is a number of bytes; otherwise it is normally 1. +/// +public sealed record ActionLogRecord +{ + public long Id { get; init; } + + public required DateTimeOffset At { get; init; } + + public required ActionKind Category { get; init; } + + public long? AccountId { get; init; } + + public long? SessionId { get; init; } + + public long Amount { get; init; } = 1; +} + +/// Usage of one budget category: rolling last 60 minutes and current local calendar day. +public readonly record struct BudgetUsage(long LastHour, long Today); + +public enum SessionOutcome +{ + /// Still open. + Running, + + /// Ended normally. + Completed, + + /// Closed by a throttle signal. + Throttled, + + /// Stopped by a challenge or disconnection, or by Alberto. + Stopped, + + /// The program ended while it was open. + Interrupted, + + /// Ended by an unexpected error. + Failed, +} + +/// A session of the engine (spec §7.2, §8.3 session): feeds the strip of the day. +public sealed record SessionRecord +{ + public long Id { get; init; } + + public required DateTimeOffset StartedAt { get; init; } + + public DateTimeOffset? EndedAt { get; init; } + + public int ActionCount { get; init; } + + public SessionOutcome Outcome { get; init; } = SessionOutcome.Running; + + /// Short Italian summary for the interface (no captions, no addresses with signatures). + public string? Summary { get; init; } +} + +/// A stop of the circuit breaker (spec §7.6, §8.3 incident). +public sealed record Incident +{ + public long Id { get; init; } + + public required DateTimeOffset At { get; init; } + + public required SignalLevel Level { get; init; } + + /// Signal code, e.g. "http-429" (from segnali.json). + public required string Signal { get; init; } + + /// Address where it was seen, without query string. + public string? Url { get; init; } + + /// For throttles: the stop lasts until this instant. + public DateTimeOffset? StoppedUntil { get; init; } + + public DateTimeOffset? ResolvedAt { get; init; } + + public long? SessionId { get; init; } + + public string? Note { get; init; } + + public bool IsOpen => ResolvedAt is null; +} + +public enum EventSeverity +{ + Info, + Success, + Warning, + Error, +} + +/// +/// A line of the readable timeline of the interface (spec §8.3 event). is Italian and +/// never contains captions, response bodies, cookies or signed addresses. +/// +public sealed record EventRecord +{ + public long Id { get; init; } + + public required DateTimeOffset At { get; init; } + + public EventSeverity Severity { get; init; } = EventSeverity.Info; + + /// Stable machine code, e.g. "storico-completato". + public required string Code { get; init; } + + public required string Message { get; init; } + + public long? AccountId { get; init; } + + public long? SessionId { get; init; } +} + +/// A profile of the list Alberto follows, as last read (spec §4.2, §8.3 following). +public sealed record FollowingRecord +{ + public string? InstagramId { get; init; } + + public required string Username { get; init; } + + public string? DisplayName { get; init; } + + public bool? IsPrivate { get; init; } + + /// Position in the list as read. + public int Position { get; init; } + + public required DateTimeOffset ReadAt { get; init; } +} diff --git a/src/Febe.Core/Domain/Entry.cs b/src/Febe.Core/Domain/Entry.cs new file mode 100644 index 0000000..2149591 --- /dev/null +++ b/src/Febe.Core/Domain/Entry.cs @@ -0,0 +1,137 @@ +using System.Text; + +namespace Febe.Core.Domain; + +/// +/// An entry («elemento», spec §4.3): one publication — a post (even with several photos and videos), a story, an item +/// of a highlight collection, a tagged post or a profile picture. Its files are rows. +/// +/// Unique per (account, kind, Instagram identifier): the same post may appear under two accounts, as a post of one and +/// as a tagged post of the other; they are two entries with two copies of the files (spec §8.3). +/// +/// +public sealed record Entry +{ + /// Local key (0 until stored). + public long Id { get; init; } + + public required long AccountId { get; init; } + + public required EntryKind Kind { get; init; } + + /// Instagram identifier, as text. Null only for imported entries that were not recognized. + public string? InstagramId { get; init; } + + /// Post code (short code), when the kind has one. + public string? Code { get; init; } + + /// Publication time, UTC. + public required DateTimeOffset PublishedAt { get; init; } + + /// Caption. Never written to logs (spec §13.2). + public string? Caption { get; init; } + + /// Author's user name, for tagged posts (the author is someone else). + public string? AuthorUsername { get; init; } + + public string? AuthorInstagramId { get; init; } + + public EntryState State { get; init; } = EntryState.ToDownload; + + public Provenance Provenance { get; init; } = Provenance.Downloaded; + + public required DateTimeOffset DiscoveredAt { get; init; } + + public DateTimeOffset? DownloadedAt { get; init; } + + /// When Alberto deleted it from the library (state ). + public DateTimeOffset? DeletedAt { get; init; } + + /// For stories: when the story stops being available on the site (downloads give them precedence). + public DateTimeOffset? ExpiresAt { get; init; } + + /// The value of the {codice} placeholder (spec §4.3) for this entry. + /// SHA-256 of the file, needed for profile pictures (first eight hex digits). + public string NameCode(string? sha256 = null) => Kind switch + { + EntryKind.Post or EntryKind.Tagged => Code ?? InstagramId ?? "senza-codice", + EntryKind.Story or EntryKind.Highlight => InstagramId ?? Code ?? "senza-codice", + EntryKind.ProfilePicture => sha256 is { Length: >= 8 } ? sha256[..8] : InstagramId ?? "profilo", + _ => Code ?? InstagramId ?? "senza-codice", + }; + + // Keeps the caption out of ToString(): records are easy to log by mistake. + private bool PrintMembers(StringBuilder builder) + { + builder.Append($"Id = {Id}, AccountId = {AccountId}, Kind = {Kind}, InstagramId = {InstagramId}, Code = {Code}, "); + builder.Append($"PublishedAt = {PublishedAt:O}, State = {State}, Provenance = {Provenance}"); + return true; + } +} + +/// An entry with its files, in position order. +public sealed record EntryWithMedia(Entry Entry, IReadOnlyList Media); + +/// Derives the state of an entry from the states of its files. +public static class EntryStateRules +{ + /// + /// State of an entry given its files. A deleted entry stays deleted; files present (downloaded or imported) and + /// files still to download give «parziale»; skipped files (a limit) are settled, not pending. + /// + public static EntryState FromMedia(EntryState current, Provenance provenance, IReadOnlyCollection media) + { + ArgumentNullException.ThrowIfNull(media); + if (current == EntryState.Deleted || media.Count == 0) + { + return current; + } + + int present = 0, pending = 0, failed = 0, imported = 0; + foreach (var state in media) + { + switch (state) + { + case MediaState.Downloaded: + present++; + break; + case MediaState.Imported: + present++; + imported++; + break; + case MediaState.ToDownload: + case MediaState.Expired: + pending++; + break; + case MediaState.Failed: + failed++; + break; + default: + break; // Skipped, Deleted: settled without a file + } + } + + if (present == media.Count) + { + return imported == media.Count || provenance == Provenance.Imported ? EntryState.Imported : EntryState.Downloaded; + } + + if (pending > 0) + { + return present > 0 ? EntryState.Partial : EntryState.ToDownload; + } + + if (failed > 0) + { + return present > 0 ? EntryState.Partial : EntryState.Failed; + } + + return present > 0 ? EntryState.Partial : EntryState.Skipped; + } + + /// States whose entries appear in the library mosaic (they have at least one file). + public static IReadOnlyList Visible { get; } = [EntryState.Downloaded, EntryState.Partial, EntryState.Imported]; + + /// True when the file state means a file is on disk. + public static bool IsPresent(MediaState state) => state is MediaState.Downloaded or MediaState.Imported; +} diff --git a/src/Febe.Core/Domain/Highlight.cs b/src/Febe.Core/Domain/Highlight.cs new file mode 100644 index 0000000..c421280 --- /dev/null +++ b/src/Febe.Core/Domain/Highlight.cs @@ -0,0 +1,33 @@ +namespace Febe.Core.Domain; + +/// +/// A highlight collection («raccolta in evidenza») pinned on a profile (spec §4.3, §8.3). Its contents are entries, +/// in order; an entry may belong to several collections, and a story already saved that enters a collection is +/// referenced, not downloaded again (hypothesis H9). +/// +public sealed record Highlight +{ + /// Local key (0 until stored). + public long Id { get; init; } + + public required long AccountId { get; init; } + + /// Instagram identifier of the collection. Null for collections known only from an import. + public string? InstagramId { get; init; } + + /// Title shown on the profile: the {raccolta} placeholder. + public required string Title { get; init; } + + /// Order on the profile, from 0. + public int Position { get; init; } + + public required DateTimeOffset DiscoveredAt { get; init; } + + public DateTimeOffset? LastCheckedAt { get; init; } + + /// The collection disappeared from the profile. Its files stay (rule 12). + public DateTimeOffset? RemovedAt { get; init; } +} + +/// An entry inside a highlight collection, with its position (from 0). +public sealed record HighlightItem(long HighlightId, long EntryId, int Position); diff --git a/src/Febe.Core/Domain/Import.cs b/src/Febe.Core/Domain/Import.cs new file mode 100644 index 0000000..95f0b96 --- /dev/null +++ b/src/Febe.Core/Domain/Import.cs @@ -0,0 +1,181 @@ +namespace Febe.Core.Domain; + +/// State of an import (spec §9.1: source, analysis, review, copy). +public enum ImportRunState +{ + /// Passo 2: read-only analysis in progress. + Analyzing, + + /// Analysis interrupted: resumes from where it was. + AnalysisInterrupted, + + /// Passo 3: waiting for Alberto's review. + Reviewing, + + /// Passo 4: copy or move in progress. + Copying, + + /// Copy interrupted: resumes from where it was. + CopyInterrupted, + + Completed, + + Cancelled, +} + +/// «Copia» (default) or «Sposta» (the original is deleted only after the copy is verified with SHA-256). +public enum ImportMode +{ + Copy, + Move, +} + +/// Result of the comparison with the library (spec §9.3). +public enum ImportOutcome +{ + /// Not analyzed yet. + Pending, + + /// «Nuovo»: will be copied. + New, + + /// «Già in libreria»: same SHA-256 as a file present in any account. Skipped. + AlreadyInLibrary, + + /// «Doppione probabile»: same Instagram identifier with a different file, or very close perceptual hash. + ProbableDuplicate, + + /// «Non riconosciuto»: neither a photo nor a video. Ignored and listed. + Unrecognized, +} + +/// Alberto's decision for a file of an import. +public enum ImportDecision +{ + /// Follow the outcome (new files are imported, the others are not). + None, + + Import, + + Skip, + + KeepLarger, + + KeepExisting, + + KeepBoth, +} + +/// Progress of one file of an import. Persisted so that an interrupted import resumes (spec §9.4). +public enum ImportFileState +{ + Pending, + Analyzed, + Copied, + Moved, + Skipped, + Failed, +} + +/// Where the date of an imported file came from (spec §9.2, in this order of preference). +public enum ImportDateSource +{ + FileName, + Metadata, + ModifiedTime, +} + +/// An import (spec §8.3 import_run). +public sealed record ImportRun +{ + public long Id { get; init; } + + /// Source folder (Windows: chosen folder; Docker: a subfolder of /importa). + public required string SourcePath { get; init; } + + /// The source cannot be written: «Sposta» is not offered. + public bool SourceReadOnly { get; init; } + + public ImportMode Mode { get; init; } = ImportMode.Copy; + + public ImportRunState State { get; init; } = ImportRunState.Analyzing; + + public required DateTimeOffset StartedAt { get; init; } + + public DateTimeOffset? AnalyzedAt { get; init; } + + public DateTimeOffset? CompletedAt { get; init; } + + public string? LastError { get; init; } +} + +/// A file of an import with its analysis, outcome and decision (spec §8.3 import_file). +public sealed record ImportFile +{ + public long Id { get; init; } + + public required long RunId { get; init; } + + /// Path relative to the source folder, '/' separated. + public required string RelativePath { get; init; } + + /// Source subfolder (relative, '/' separated, empty for the root): the unit of account association. + public required string Folder { get; init; } + + public long Bytes { get; init; } + + public DateTimeOffset? ModifiedAt { get; init; } + + /// Photo or video from the content; null when not recognized. + public MediaKind? MediaKind { get; init; } + + /// Detected content type, e.g. "image/jpeg". + public string? ContentType { get; init; } + + public int? Width { get; init; } + + public int? Height { get; init; } + + public TimeSpan? Duration { get; init; } + + public string? Sha256 { get; init; } + + public ulong? PerceptualHash { get; init; } + + public DateTimeOffset? TakenAt { get; init; } + + public ImportDateSource? DateSource { get; init; } + + public string? InstagramId { get; init; } + + public string? Code { get; init; } + + /// Probable account, from the folder name. + public string? ProbableAccount { get; init; } + + /// Probable kind (story, highlight, tagged) from the subfolders. + public EntryKind? ProbableKind { get; init; } + + /// Probable highlight collection title, from the subfolders. + public string? HighlightTitle { get; init; } + + public ImportOutcome Outcome { get; init; } = ImportOutcome.Pending; + + /// The library file this one matches (already in library or probable duplicate). + public long? MatchedMediaId { get; init; } + + /// Account the folder is associated with in the review. + public long? TargetAccountId { get; init; } + + public ImportDecision Decision { get; init; } = ImportDecision.None; + + public ImportFileState State { get; init; } = ImportFileState.Pending; + + /// Entry created or completed by the copy. + public long? EntryId { get; init; } + + /// Path of the copy relative to the account folder. + public string? DestinationPath { get; init; } + + public string? LastError { get; init; } +} diff --git a/src/Febe.Core/Domain/LocalCalendar.cs b/src/Febe.Core/Domain/LocalCalendar.cs new file mode 100644 index 0000000..9c87b08 --- /dev/null +++ b/src/Febe.Core/Domain/LocalCalendar.cs @@ -0,0 +1,59 @@ +namespace Febe.Core.Domain; + +/// +/// Calendar days in Alberto's time zone (spec §7.4: daily budgets use the local calendar day; §4.7: dates in file +/// names are local). The database stores UTC instants; these helpers convert at the edges. +/// +public static class LocalCalendar +{ + /// Local calendar day of an instant. + public static DateOnly Today(DateTimeOffset instant, TimeZoneInfo zone) => + DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(instant, zone).DateTime); + + /// Local wall-clock time of an instant. + public static DateTime ToLocal(DateTimeOffset instant, TimeZoneInfo zone) => + TimeZoneInfo.ConvertTime(instant, zone).DateTime; + + /// + /// First instant of a local day. If local midnight does not exist (a daylight-saving jump at midnight, as in some + /// zones) the first valid local time after it is used. + /// + public static DateTimeOffset StartOfDay(DateOnly day, TimeZoneInfo zone) => + FromLocal(day.ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified), zone); + + /// [start, end) of a local day, as UTC instants. + public static (DateTimeOffset Start, DateTimeOffset End) DayBounds(DateOnly day, TimeZoneInfo zone) => + (StartOfDay(day, zone), StartOfDay(day.AddDays(1), zone)); + + /// [start, end) of the local day containing . + public static (DateTimeOffset Start, DateTimeOffset End) DayBounds(DateTimeOffset instant, TimeZoneInfo zone) => + DayBounds(Today(instant, zone), zone); + + /// + /// Converts a local wall-clock time to an instant. Invalid times (inside a spring-forward gap) move forward to the + /// first valid minute; ambiguous times (fall-back) take the earlier instant (daylight time). + /// + public static DateTimeOffset FromLocal(DateTime local, TimeZoneInfo zone) + { + ArgumentNullException.ThrowIfNull(zone); + var unspecified = DateTime.SpecifyKind(local, DateTimeKind.Unspecified); + var probe = unspecified; + for (var i = 0; i < 24 * 60 && zone.IsInvalidTime(probe); i++) + { + probe = probe.AddMinutes(1); + } + + TimeSpan offset; + if (zone.IsAmbiguousTime(probe)) + { + var offsets = zone.GetAmbiguousTimeOffsets(probe); + offset = offsets.Max(); + } + else + { + offset = zone.GetUtcOffset(probe); + } + + return new DateTimeOffset(probe, offset).ToUniversalTime(); + } +} diff --git a/src/Febe.Core/Domain/Media.cs b/src/Febe.Core/Domain/Media.cs new file mode 100644 index 0000000..10b0a0a --- /dev/null +++ b/src/Febe.Core/Domain/Media.cs @@ -0,0 +1,98 @@ +using System.Text; + +namespace Febe.Core.Domain; + +/// +/// A file («file», spec §4.3): one photo or one video of an entry. Unique per (entry, position). +/// +public sealed record Media +{ + /// Local key (0 until stored). + public long Id { get; init; } + + /// Owning entry (set by the store when the entry is added). + public long EntryId { get; init; } + + /// Position in the series, from 1: the {n} placeholder. + public required int Position { get; init; } + + public required MediaKind Kind { get; init; } + + /// Instagram identifier of this item of a series, when the site gives one. + public string? InstagramId { get; init; } + + public int? Width { get; init; } + + public int? Height { get; init; } + + /// Video duration. + public TimeSpan? Duration { get; init; } + + public MediaState State { get; init; } = MediaState.ToDownload; + + /// Path relative to the account folder, with '/' separators. Null while not on disk. + public string? RelativePath { get; init; } + + public long? Bytes { get; init; } + + /// SHA-256 of the file, lowercase hex: exact duplicates and thumbnail key. + public string? Sha256 { get; init; } + + /// 64-bit perceptual hash, for photos only (spec §8.4). + public ulong? PerceptualHash { get; init; } + + /// A thumbnail exists under Dati/miniature for . + public bool HasThumbnail { get; init; } + + /// + /// Address of the best version, as given by the page. It is signed and expires: kept only until the file is + /// downloaded and never logged (spec §13.2). + /// + public string? SourceUrl { get; init; } + + /// Address of the video cover image given by the page (thumbnail source for videos). + public string? CoverUrl { get; init; } + + /// When was read from the page. + public DateTimeOffset? SourceSeenAt { get; init; } + + public int Attempts { get; init; } + + /// Last error, in Italian, without addresses or secrets. + public string? LastError { get; init; } + + public DateTimeOffset? DownloadedAt { get; init; } + + // Keeps signed addresses out of ToString(): records are easy to log by mistake. + private bool PrintMembers(StringBuilder builder) + { + builder.Append($"Id = {Id}, EntryId = {EntryId}, Position = {Position}, Kind = {Kind}, State = {State}, "); + builder.Append($"RelativePath = {RelativePath}, Bytes = {Bytes}, Sha256 = {Sha256}, Attempts = {Attempts}"); + return true; + } +} + +/// A file together with where it lives: used by exact-duplicate lookups across the library. +public sealed record MediaLocation(Media Media, Entry Entry, string Username); + +/// A file waiting for the download queue (spec §6.5), with what the queue needs to order it. +public sealed record PendingDownload(Media Media, long AccountId, EntryKind Kind, DateTimeOffset PublishedAt, DateTimeOffset? ExpiresAt); + +/// What the safe writer and the hashing produced for a file now on disk. +/// Path relative to the account folder, '/' separated. +/// Size. +/// Lowercase hex SHA-256. +/// Perceptual hash for photos. +/// Width in pixels, when known. +/// Height in pixels, when known. +/// Video duration, when known. +/// A thumbnail was stored. +public sealed record StoredFile( + string RelativePath, + long Bytes, + string Sha256, + ulong? PerceptualHash = null, + int? Width = null, + int? Height = null, + TimeSpan? Duration = null, + bool HasThumbnail = false); diff --git a/src/Febe.Core/Library/AccountJournal.cs b/src/Febe.Core/Library/AccountJournal.cs new file mode 100644 index 0000000..761f3e9 --- /dev/null +++ b/src/Febe.Core/Library/AccountJournal.cs @@ -0,0 +1,293 @@ +using System.Collections.Concurrent; +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using Febe.Core.Abstractions; +using Febe.Core.Domain; + +namespace Febe.Core.Library; + +/// Operations recorded in _febe.jsonl. +public static class JournalOps +{ + /// An entry was saved (or completed): one line per saved entry. + public const string Save = "save"; + + /// An entry was deleted from the library by Alberto. + public const string Delete = "delete"; +} + +/// Account identity in a journal line. +public sealed record JournalAccount(string? Id, string Username, string? DisplayName = null, bool? IsMine = null); + +/// A highlight collection an entry belongs to. +public sealed record JournalHighlight(string? Id, string Title, int? Position = null); + +/// Entry data in a journal line. is the folder name of the kind («post», «storie», ...). +public sealed record JournalEntry +{ + public required string Kind { get; init; } + + public string? Id { get; init; } + + public string? Code { get; init; } + + public required DateTimeOffset PublishedAt { get; init; } + + public string? Caption { get; init; } + + public string? Author { get; init; } + + public string? AuthorId { get; init; } + + /// "downloaded" or "imported". + public string? Provenance { get; init; } + + public DateTimeOffset? ExpiresAt { get; init; } + + public IReadOnlyList? Highlights { get; init; } +} + +/// A file in a journal line; is relative to the account folder, '/' separated. +public sealed record JournalFile +{ + public required int N { get; init; } + + /// "photo" or "video". + public string? Type { get; init; } + + public required string Path { get; init; } + + public long? Bytes { get; init; } + + public string? Sha256 { get; init; } + + public int? Width { get; init; } + + public int? Height { get; init; } + + public long? DurationMs { get; init; } + + public string? Id { get; init; } +} + +/// One line of _febe.jsonl (format version 1). +public sealed record JournalLine +{ + public int V { get; init; } = AccountJournal.FormatVersion; + + /// or . + public required string Op { get; init; } + + public required DateTimeOffset At { get; init; } + + public required JournalAccount Account { get; init; } + + public required JournalEntry Entry { get; init; } + + public IReadOnlyList? Files { get; init; } + + /// Delete only: true when the deletion is remembered (the entry must not come back). + public bool? Remember { get; init; } + + /// The entry kind of this line, or null for an unknown kind name. + [JsonIgnore] + public EntryKind? Kind => EntryKindNames.FromFolder(Entry.Kind); +} + +/// Content of a journal: the valid lines in order, and how many lines could not be read. +public sealed record JournalContent(IReadOnlyList Lines, int InvalidLines); + +/// +/// The journal of an account folder, _febe.jsonl (spec §8.5): one JSON line per saved entry (identifiers, dates, +/// caption, file names) and one per deletion. Lines are only appended, never rewritten. With the files it lets the +/// database be rebuilt without downloading anything again (). +/// +public sealed class AccountJournal(IClock clock) +{ + /// File name inside each account folder. + public const string FileName = "_febe.jsonl"; + + public const int FormatVersion = 1; + + private static readonly ConcurrentDictionary Locks = new( + OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + + internal static JsonSerializerOptions Options { get; } = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, // readable accents; the file is never embedded in HTML + TypeInfoResolver = JournalJsonContext.Default, + WriteIndented = false, + }; + + /// Path of the journal of an account folder. + public static string PathFor(string accountFolder) => Path.Combine(accountFolder, FileName); + + /// Appends the line of a saved entry: the files present (downloaded or imported) with their metadata. + public Task AppendSavedAsync( + string accountFolder, + Account account, + Entry entry, + IReadOnlyList media, + IReadOnlyList? highlights = null, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(media); + var line = new JournalLine + { + Op = JournalOps.Save, + At = clock.Now.ToUniversalTime(), + Account = AccountOf(account), + Entry = EntryOf(entry) with { Highlights = highlights is { Count: > 0 } ? highlights : null }, + Files = media + .Where(m => EntryStateRules.IsPresent(m.State) && m.RelativePath is not null) + .OrderBy(m => m.Position) + .Select(m => new JournalFile + { + N = m.Position, + Type = m.Kind == MediaKind.Video ? "video" : "photo", + Path = LibraryLayout.ToStored(m.RelativePath!), + Bytes = m.Bytes, + Sha256 = m.Sha256, + Width = m.Width, + Height = m.Height, + DurationMs = m.Duration is { } d ? (long)d.TotalMilliseconds : null, + Id = m.InstagramId, + }) + .ToList(), + }; + return AppendAsync(accountFolder, line, ct); + } + + /// + /// Appends the line of a deletion. With the entry stays known and is not downloaded + /// again; without it («Eliminalo e lascia che torni») it may come back. + /// + public Task AppendDeletedAsync( + string accountFolder, + Account account, + Entry entry, + IReadOnlyList deletedPaths, + bool remember, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(deletedPaths); + var identity = EntryOf(entry) with { Caption = null, Author = null, AuthorId = null }; + var line = new JournalLine + { + Op = JournalOps.Delete, + At = clock.Now.ToUniversalTime(), + Account = AccountOf(account), + Entry = identity, + Files = deletedPaths.Select((p, i) => new JournalFile { N = i + 1, Path = LibraryLayout.ToStored(p) }).ToList(), + Remember = remember, + }; + return AppendAsync(accountFolder, line, ct); + } + + /// Appends a line. Lines of one file are serialized; a line cut by a crash never merges with the next. + public static async Task AppendAsync(string accountFolder, JournalLine line, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(accountFolder); + ArgumentNullException.ThrowIfNull(line); + var path = Path.GetFullPath(PathFor(accountFolder)); + var json = JsonSerializer.Serialize(line, Options); + var bytes = Encoding.UTF8.GetBytes(json + "\n"); + + var gate = Locks.GetOrAdd(path, _ => new SemaphoreSlim(1, 1)); + await gate.WaitAsync(ct).ConfigureAwait(false); + try + { + Directory.CreateDirectory(accountFolder); + await using var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.Asynchronous); + if (stream.Length > 0) + { + stream.Seek(-1, SeekOrigin.End); + var last = new byte[1]; + if (await stream.ReadAsync(last, ct).ConfigureAwait(false) == 1 && last[0] != (byte)'\n') + { + // The previous line was cut by a crash: end it so the new line stays readable. + stream.Seek(0, SeekOrigin.End); + await stream.WriteAsync("\n"u8.ToArray(), ct).ConfigureAwait(false); + } + } + + stream.Seek(0, SeekOrigin.End); + await stream.WriteAsync(bytes, ct).ConfigureAwait(false); + await stream.FlushAsync(ct).ConfigureAwait(false); + stream.Flush(flushToDisk: true); + } + finally + { + gate.Release(); + } + } + + /// Reads a journal. Unreadable lines (e.g. cut by a crash) are counted and skipped. + public static async Task ReadAsync(string accountFolder, CancellationToken ct = default) + { + var path = PathFor(accountFolder); + if (!File.Exists(path)) + { + return new JournalContent([], 0); + } + + var lines = new List(); + var invalid = 0; + await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan); + using var reader = new StreamReader(stream, Encoding.UTF8); + while (await reader.ReadLineAsync(ct).ConfigureAwait(false) is { } text) + { + if (string.IsNullOrWhiteSpace(text)) + { + continue; + } + + try + { + var line = JsonSerializer.Deserialize(text, JournalJsonContext.Default.JournalLine); + if (line is { Op: JournalOps.Save or JournalOps.Delete, Account.Username.Length: > 0, Entry.Kind.Length: > 0 }) + { + lines.Add(line); + } + else + { + invalid++; + } + } + catch (JsonException) + { + invalid++; + } + } + + return new JournalContent(lines, invalid); + } + + internal static JournalAccount AccountOf(Account account) => + new(account.InstagramId, account.Username, account.DisplayName, account.IsMine ? true : null); + + internal static JournalEntry EntryOf(Entry entry) => new() + { + Kind = EntryKindNames.Folder(entry.Kind), + Id = entry.InstagramId, + Code = entry.Code, + PublishedAt = entry.PublishedAt.ToUniversalTime(), + Caption = entry.Caption, + Author = entry.AuthorUsername, + AuthorId = entry.AuthorInstagramId, + Provenance = entry.Provenance == Provenance.Imported ? "imported" : "downloaded", + ExpiresAt = entry.ExpiresAt?.ToUniversalTime(), + }; +} + +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +[JsonSerializable(typeof(JournalLine))] +internal sealed partial class JournalJsonContext : JsonSerializerContext; diff --git a/src/Febe.Core/Library/DailyBackup.cs b/src/Febe.Core/Library/DailyBackup.cs new file mode 100644 index 0000000..09ae4b9 --- /dev/null +++ b/src/Febe.Core/Library/DailyBackup.cs @@ -0,0 +1,123 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Library; + +/// A daily copy of the database. +public sealed record BackupFile(DateOnly Day, string Path, long Bytes); + +/// Result of a daily backup run. +/// The copy made now, or null when today's copy already existed. +/// Copies removed by the retention. +public sealed record BackupResult(BackupFile? Created, IReadOnlyList Removed); + +/// +/// Daily copy of the database (spec §8.5): VACUUM INTO a new file Dati/copie/febe-YYYY-MM-DD.sqlite +/// (local date), keeping seven days. A copy is written under a temporary name and renamed, so a cut copy never has a +/// final name. Only files named febe-YYYY-MM-DD.sqlite are ever removed. +/// +public sealed partial class DailyBackup(IDatabaseMaintenance database, IClock clock, string backupsFolder, int keepDays = DailyBackup.DefaultKeepDays) +{ + public const int DefaultKeepDays = 7; + + private const string Prefix = "febe-"; + private const string Extension = ".sqlite"; + private const string PartSuffix = ".part"; + + [GeneratedRegex(@"^febe-(\d{4}-\d{2}-\d{2})\.sqlite$", RegexOptions.CultureInvariant)] + private static partial Regex BackupName(); + + /// The backups folder. + public string Folder { get; } = Path.GetFullPath(backupsFolder); + + /// File name of the copy of a day. + public static string FileNameFor(DateOnly day) => Prefix + day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + Extension; + + /// Makes today's copy if missing, then applies the retention. Safe to call often. + public async Task RunAsync(CancellationToken ct = default) + { + Directory.CreateDirectory(Folder); + var today = LocalCalendar.Today(clock.Now, clock.LocalZone); + var target = Path.Combine(Folder, FileNameFor(today)); + BackupFile? created = null; + if (!File.Exists(target)) + { + var part = target + "." + Guid.NewGuid().ToString("N")[..8] + PartSuffix; + try + { + await database.BackupToAsync(part, ct).ConfigureAwait(false); + File.Move(part, target, overwrite: false); + created = new BackupFile(today, target, new FileInfo(target).Length); + } + finally + { + if (File.Exists(part)) + { + File.Delete(part); + } + } + } + + return new BackupResult(created, ApplyRetention(today)); + } + + /// The copies present, newest first. + public IReadOnlyList List() + { + if (!Directory.Exists(Folder)) + { + return []; + } + + var list = new List(); + foreach (var file in Directory.EnumerateFiles(Folder, Prefix + "*" + Extension)) + { + if (TryParseDay(Path.GetFileName(file)) is { } day) + { + list.Add(new BackupFile(day, file, new FileInfo(file).Length)); + } + } + + return list.OrderByDescending(b => b.Day).ToList(); + } + + /// + /// Removes copies older than days (today included) and stale temporary copies. + /// Returns the removed paths. + /// + public IReadOnlyList ApplyRetention(DateOnly today) + { + var removed = new List(); + if (!Directory.Exists(Folder)) + { + return removed; + } + + var oldestKept = today.AddDays(-(Math.Max(1, keepDays) - 1)); + foreach (var backup in List().Where(b => b.Day < oldestKept)) + { + File.Delete(backup.Path); + removed.Add(backup.Path); + } + + foreach (var part in Directory.EnumerateFiles(Folder, Prefix + "*" + PartSuffix)) + { + File.Delete(part); + removed.Add(part); + } + + return removed; + } + + /// The day of a backup file name, or null for any other file. + public static DateOnly? TryParseDay(string fileName) + { + var match = BackupName().Match(fileName); + return match.Success && DateOnly.TryParseExact(match.Groups[1].Value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) + ? day + : null; + } +} diff --git a/src/Febe.Core/Library/DataFolderCheck.cs b/src/Febe.Core/Library/DataFolderCheck.cs new file mode 100644 index 0000000..8b99e61 --- /dev/null +++ b/src/Febe.Core/Library/DataFolderCheck.cs @@ -0,0 +1,328 @@ +using System.Text; + +namespace Febe.Core.Library; + +/// What is wrong with the Data folder. +public enum DataFolderProblemKind +{ + /// On a network share: SQLite in WAL mode and the browser profile do not work there (spec §8.2). + NetworkPath, + + /// The folder cannot be written. + NotWritable, + + /// The folder does not exist and cannot be created. + CannotCreate, + + /// The path names a file, not a folder. + NotAFolder, +} + +/// +/// A problem of the Data folder, written for the error page (spec §8.2, §10.3, §11): what happened, what Febe did, +/// what Alberto should do. While there is a problem the engine does not start. +/// +public sealed record DataFolderProblem( + DataFolderProblemKind Kind, + string Path, + string Title, + string Explanation, + string Remedy, + string? FileSystem = null); + +/// A mounted file system (a line of /proc/mounts). +public sealed record MountEntry(string Device, string MountPoint, string FileSystemType); + +/// Reads mount tables (Linux /proc/mounts). +public static class MountTable +{ + /// + /// File system types that live on another machine. 9p is included: it is how WSL and some virtual machines + /// share host folders, and SQLite's locking is not reliable on it. + /// + public static IReadOnlySet NetworkFileSystems { get; } = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "nfs", "nfs4", "cifs", "smb", "smb2", "smb3", "smbfs", "ncpfs", "afs", "9p", "ceph", "glusterfs", "lustre", "gpfs", + "beegfs", "ocfs2", "gfs2", "davfs", "coda", "pvfs2", "orangefs", + "fuse.sshfs", "sshfs", "fuse.glusterfs", "fuse.cephfs", "fuse.rclone", "fuse.s3fs", "fuse.davfs2", "fuse.smbnetfs", + "fuse.gcsfuse", "fuse.goofys", "fuse.juicefs", "fuse.lizardfs", "fuse.moosefs", "fuse.seaweedfs", + }; + + public static bool IsNetworkFileSystem(string fileSystemType) + { + ArgumentNullException.ThrowIfNull(fileSystemType); + return NetworkFileSystems.Contains(fileSystemType) + || fileSystemType.StartsWith("nfs", StringComparison.OrdinalIgnoreCase) + || fileSystemType.StartsWith("smb", StringComparison.OrdinalIgnoreCase); + } + + /// Parses the content of /proc/mounts (or /etc/mtab). Malformed lines are skipped. + public static IReadOnlyList Parse(string content) + { + ArgumentNullException.ThrowIfNull(content); + var entries = new List(); + foreach (var raw in content.Split('\n')) + { + var line = raw.Trim(); + if (line.Length == 0 || line.StartsWith('#')) + { + continue; + } + + var fields = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries); + if (fields.Length < 3) + { + continue; + } + + entries.Add(new MountEntry(Unescape(fields[0]), Unescape(fields[1]), fields[2])); + } + + return entries; + } + + /// The mount that contains a path: the longest mount point that is a prefix of it (later mounts win ties). + public static MountEntry? FindContaining(IReadOnlyList mounts, string fullPath) + { + ArgumentNullException.ThrowIfNull(mounts); + ArgumentNullException.ThrowIfNull(fullPath); + MountEntry? best = null; + foreach (var mount in mounts) + { + var point = mount.MountPoint.Length > 1 ? mount.MountPoint.TrimEnd('/') : mount.MountPoint; + var contains = point == "/" + || string.Equals(fullPath, point, StringComparison.Ordinal) + || fullPath.StartsWith(point + "/", StringComparison.Ordinal); + if (contains && (best is null || point.Length >= best.MountPoint.TrimEnd('/').Length)) + { + best = mount; + } + } + + return best; + } + + /// Decodes the octal escapes of /proc/mounts (\040 space, \011 tab, \012 newline, \134 backslash). + public static string Unescape(string field) + { + ArgumentNullException.ThrowIfNull(field); + if (!field.Contains('\\', StringComparison.Ordinal)) + { + return field; + } + + var builder = new StringBuilder(field.Length); + for (var i = 0; i < field.Length; i++) + { + if (field[i] == '\\' && i + 3 < field.Length && IsOctal(field[i + 1]) && IsOctal(field[i + 2]) && IsOctal(field[i + 3])) + { + builder.Append((char)(((field[i + 1] - '0') * 64) + ((field[i + 2] - '0') * 8) + (field[i + 3] - '0'))); + i += 3; + } + else + { + builder.Append(field[i]); + } + } + + return builder.ToString(); + } + + private static bool IsOctal(char ch) => ch is >= '0' and <= '7'; +} + +/// +/// Checks the Data folder at start-up (spec §8.2, §11): it must be a local disk (Windows: not a UNC path nor a mapped +/// network drive; Linux: not an nfs, cifs/smb, sshfs, 9p, ... mount) and writable. On a problem the engine does not +/// start and the interface shows only the page that explains it. +/// +public sealed class DataFolderCheck +{ + private readonly Func _readMounts; + + /// Source of the mount table (tests inject one); by default /proc/mounts on Linux. + public DataFolderCheck(Func? readMounts = null) => _readMounts = readMounts ?? ReadProcMounts; + + /// The first problem of the folder, or null when it is fine. Creates the folder if missing. + public DataFolderProblem? Check(string path) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + var full = Path.GetFullPath(path); + + if (DetectNetwork(full) is { } network) + { + return network; + } + + if (File.Exists(full)) + { + return new DataFolderProblem( + DataFolderProblemKind.NotAFolder, + full, + "La cartella dei dati è un file", + $"Il percorso indicato per i dati, {full}, è un file e non una cartella. Il motore non è partito.", + "Indica una cartella su un disco locale, per esempio una cartella vuota creata apposta, e riavvia Febe."); + } + + try + { + Directory.CreateDirectory(full); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException) + { + return new DataFolderProblem( + DataFolderProblemKind.CannotCreate, + full, + "Febe non riesce a creare la cartella dei dati", + $"La cartella {full} non esiste e Febe non è riuscito a crearla. Il motore non è partito.", + RemedyForPermissions()); + } + + var probe = Path.Combine(full, ".febe-prova-scrittura-" + Guid.NewGuid().ToString("N")[..8]); + try + { + File.WriteAllBytes(probe, [1, 2, 3]); + File.Delete(probe); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return new DataFolderProblem( + DataFolderProblemKind.NotWritable, + full, + "Febe non può scrivere nella cartella dei dati", + $"La cartella {full} esiste ma Febe non riesce a scriverci: lì vanno il database, la sessione del browser e le copie. Il motore non è partito.", + RemedyForPermissions()); + } + + return null; + } + + /// A network-path problem for a full path, or null when the path is local. + public DataFolderProblem? DetectNetwork(string fullPath) + { + ArgumentNullException.ThrowIfNull(fullPath); + if (IsUncPath(fullPath)) + { + return NetworkProblem(fullPath, null); + } + + if (OperatingSystem.IsWindows()) + { + try + { + var root = Path.GetPathRoot(fullPath); + if (!string.IsNullOrEmpty(root) && new DriveInfo(root).DriveType == DriveType.Network) + { + return NetworkProblem(fullPath, null); + } + } + catch (ArgumentException) + { + // Not a drive path: nothing more to check. + } + + return null; + } + + var content = _readMounts(); + if (string.IsNullOrEmpty(content)) + { + return null; // no mount table (e.g. macOS): cannot tell, assume local + } + + var mount = MountTable.FindContaining(MountTable.Parse(content), ResolveExisting(fullPath)); + return mount is not null && MountTable.IsNetworkFileSystem(mount.FileSystemType) + ? NetworkProblem(fullPath, mount.FileSystemType) + : null; + } + + /// + /// True for Windows network paths: \\server\share, //server/share and \\?\UNC\server\share. + /// Device paths to local drives (\\?\C:\, \\.\C:\) are not network paths. + /// + public static bool IsUncPath(string path) + { + ArgumentNullException.ThrowIfNull(path); + var p = path.Replace('/', '\\'); + if (p.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase) || p.StartsWith(@"\\.\UNC\", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (p.StartsWith(@"\\?\", StringComparison.Ordinal) || p.StartsWith(@"\\.\", StringComparison.Ordinal)) + { + return false; + } + + // On Linux a path like //server/share is a plain absolute path: only backslash UNC forms count there. + return OperatingSystem.IsWindows() + ? p.StartsWith(@"\\", StringComparison.Ordinal) && p.Length > 2 && p[2] != '\\' + : path.StartsWith(@"\\", StringComparison.Ordinal) && path.Length > 2 && path[2] != '\\'; + } + + private static DataFolderProblem NetworkProblem(string path, string? fileSystem) => new( + DataFolderProblemKind.NetworkPath, + path, + "La cartella dei dati è su un disco di rete", + fileSystem is null + ? $"Febe ha trovato la cartella dei dati su {path}, che è una condivisione di rete. Il database e il profilo del browser non funzionano in modo affidabile su un disco di rete, quindi il motore non è partito." + : $"Febe ha trovato la cartella dei dati su {path}, che è una condivisione di rete ({fileSystem}). Il database e il profilo del browser non funzionano in modo affidabile su un disco di rete, quindi il motore non è partito.", + OperatingSystem.IsWindows() + ? "Scegli una cartella su un disco di questo computer (per esempio quella predefinita in %LOCALAPPDATA%\\Febe) e riavvia Febe. La Libreria invece può stare anche su un disco di rete." + : "Collega /dati a una cartella su un disco locale del server (su Unraid: la cartella delle applicazioni sul disco di cache) e riavvia il contenitore. La Libreria invece può stare anche su una condivisione.", + fileSystem); + + private static string RemedyForPermissions() => OperatingSystem.IsWindows() + ? "Controlla che la cartella non sia in sola lettura e che il tuo utente possa scriverci, oppure scegline un'altra su un disco locale, poi riavvia Febe." + : "Controlla i permessi della cartella: in Docker l'utente del contenitore è quello di PUID e PGID (su Unraid 99 e 100). Poi riavvia il contenitore."; + + /// The path with symbolic links of its existing part resolved, so the right mount is found. + private static string ResolveExisting(string fullPath) + { + var current = fullPath; + var suffix = new Stack(); + while (!Directory.Exists(current) && !File.Exists(current)) + { + var parent = Path.GetDirectoryName(current); + if (string.IsNullOrEmpty(parent) || parent == current) + { + return fullPath; + } + + suffix.Push(Path.GetFileName(current)); + current = parent; + } + + try + { + var resolved = new DirectoryInfo(current).ResolveLinkTarget(returnFinalTarget: true)?.FullName ?? current; + while (suffix.Count > 0) + { + resolved = Path.Combine(resolved, suffix.Pop()); + } + + return resolved; + } + catch (IOException) + { + return fullPath; + } + } + + private static string? ReadProcMounts() + { + if (!OperatingSystem.IsLinux()) + { + return null; + } + + try + { + return File.Exists("/proc/self/mounts") ? File.ReadAllText("/proc/self/mounts") : File.ReadAllText("/proc/mounts"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } +} diff --git a/src/Febe.Core/Library/ImageDecoding.cs b/src/Febe.Core/Library/ImageDecoding.cs new file mode 100644 index 0000000..f0941c4 --- /dev/null +++ b/src/Febe.Core/Library/ImageDecoding.cs @@ -0,0 +1,131 @@ +using SkiaSharp; + +namespace Febe.Core.Library; + +/// +/// Decodes images with SkiaSharp, applying the EXIF orientation (photos from phones) and, when the codec allows it, +/// decoding directly at a reduced size to save memory and time. +/// +internal static class ImageDecoding +{ + /// + /// Images larger than this (after the codec's own reduction) are not decoded: a 100-megapixel PNG would need 400 MB. + /// Such files simply get no thumbnail and no perceptual hash. + /// + public const long MaxDecodedPixels = 100_000_000; + + /// + /// Decodes an image upright, as premultiplied RGBA. When is given the codec may + /// decode at a lower resolution, but never below that long side (unless the image is smaller). + /// Returns null when the content is not a decodable image. + /// + public static SKBitmap? DecodeUpright(Stream stream, int? minLongSide = null) + { + ArgumentNullException.ThrowIfNull(stream); + using var data = SKData.Create(stream); + if (data is null || data.IsEmpty) + { + return null; + } + + using var codec = SKCodec.Create(data); + if (codec is null) + { + return null; + } + + var size = ChooseDecodeSize(codec, minLongSide); + if ((long)size.Width * size.Height > MaxDecodedPixels || size.Width <= 0 || size.Height <= 0) + { + return null; + } + + var info = new SKImageInfo(size.Width, size.Height, SKColorType.Rgba8888, SKAlphaType.Premul); + var decoded = new SKBitmap(info); + var result = codec.GetPixels(info, decoded.GetPixels()); + if (result is not (SKCodecResult.Success or SKCodecResult.IncompleteInput)) + { + decoded.Dispose(); + return null; + } + + return Orient(decoded, codec.EncodedOrigin); + } + + /// Dimensions of an image as displayed (orientation applied), without decoding the pixels. + public static (int Width, int Height)? ReadSize(Stream stream) + { + ArgumentNullException.ThrowIfNull(stream); + using var codec = SKCodec.Create(stream); + if (codec is null) + { + return null; + } + + var (w, h) = (codec.Info.Width, codec.Info.Height); + return SwapsAxes(codec.EncodedOrigin) ? (h, w) : (w, h); + } + + private static SKSizeI ChooseDecodeSize(SKCodec codec, int? minLongSide) + { + var full = new SKSizeI(codec.Info.Width, codec.Info.Height); + if (minLongSide is not { } min || Math.Max(full.Width, full.Height) <= min) + { + return full; + } + + var best = full; + foreach (var scale in new[] { 0.5f, 0.25f, 0.125f }) + { + var scaled = codec.GetScaledDimensions(scale); + if (scaled.Width <= 0 || scaled.Height <= 0 || Math.Max(scaled.Width, scaled.Height) < min) + { + break; + } + + best = scaled; + } + + return best; + } + + private static bool SwapsAxes(SKEncodedOrigin origin) => + origin is SKEncodedOrigin.LeftTop or SKEncodedOrigin.RightTop or SKEncodedOrigin.RightBottom or SKEncodedOrigin.LeftBottom; + + private static SKBitmap Orient(SKBitmap source, SKEncodedOrigin origin) + { + if (origin is SKEncodedOrigin.TopLeft or SKEncodedOrigin.Default) + { + return source; + } + + float w = source.Width, h = source.Height; + var swap = SwapsAxes(origin); + var outW = swap ? source.Height : source.Width; + var outH = swap ? source.Width : source.Height; + + // Each matrix maps a source pixel (x, y) to its upright position. + var matrix = origin switch + { + SKEncodedOrigin.TopRight => new SKMatrix(-1, 0, w, 0, 1, 0, 0, 0, 1), + SKEncodedOrigin.BottomRight => new SKMatrix(-1, 0, w, 0, -1, h, 0, 0, 1), + SKEncodedOrigin.BottomLeft => new SKMatrix(1, 0, 0, 0, -1, h, 0, 0, 1), + SKEncodedOrigin.LeftTop => new SKMatrix(0, 1, 0, 1, 0, 0, 0, 0, 1), + SKEncodedOrigin.RightTop => new SKMatrix(0, -1, h, 1, 0, 0, 0, 0, 1), + SKEncodedOrigin.RightBottom => new SKMatrix(0, -1, h, -1, 0, w, 0, 0, 1), + SKEncodedOrigin.LeftBottom => new SKMatrix(0, 1, 0, -1, 0, w, 0, 0, 1), + _ => SKMatrix.Identity, + }; + + var upright = new SKBitmap(new SKImageInfo(outW, outH, SKColorType.Rgba8888, SKAlphaType.Premul)); + using (var canvas = new SKCanvas(upright)) + { + canvas.Clear(SKColors.Transparent); + canvas.SetMatrix(in matrix); + canvas.DrawBitmap(source, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest), null); + } + + source.Dispose(); + return upright; + } +} diff --git a/src/Febe.Core/Library/LibraryDeletion.cs b/src/Febe.Core/Library/LibraryDeletion.cs new file mode 100644 index 0000000..e560701 --- /dev/null +++ b/src/Febe.Core/Library/LibraryDeletion.cs @@ -0,0 +1,146 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Library; + +/// The two choices of the deletion dialog (spec §4.6). +public enum DeletionMode +{ + /// + /// Default, «ricorda la scelta»: the entry stays in the database without files, in the state «eliminato», so it is + /// never downloaded again. + /// + Remember, + + /// «Eliminalo e lascia che torni»: the record is removed too; a later check may download it again. + AllowReturn, +} + +/// What a deletion did. +/// The entry. +/// False when the entry did not exist (nothing done). +/// Files removed from disk (relative paths). +/// Files that were already missing. +/// Files that could not be removed (e.g. open in another program), with the reason. +public sealed record DeletionResult( + long EntryId, + bool Found, + IReadOnlyList DeletedFiles, + IReadOnlyList MissingFiles, + IReadOnlyList FailedFiles) +{ + public bool Complete => Found && FailedFiles.Count == 0; +} + +/// +/// «Elimina dalla libreria» (spec §4.6). The confirmation is the interface's job; this class runs only on an explicit +/// choice of Alberto (rule 12: the library never deletes or replaces files on its own). +/// +/// Order: the deletion line goes to _febe.jsonl first (so a rebuild honours it even if Febe stops halfway), +/// then the database, then the files and their thumbnails. +/// +/// +public sealed class LibraryDeletion( + IFebeStorage storage, + LibraryLayout layout, + AccountJournal journal, + IClock clock, + ThumbnailStore? thumbnails = null, + PerceptualHashIndex? hashIndex = null) +{ + public async Task DeleteAsync(long entryId, DeletionMode mode = DeletionMode.Remember, CancellationToken ct = default) + { + var stored = await storage.Entries.GetWithMediaAsync(entryId, ct).ConfigureAwait(false); + if (stored is null) + { + return new DeletionResult(entryId, false, [], [], []); + } + + var account = await storage.Accounts.GetAsync(stored.Entry.AccountId, ct).ConfigureAwait(false) + ?? throw new InvalidOperationException($"L'account dell'elemento {entryId} non esiste."); + var folder = layout.AccountFolder(account); + var present = stored.Media.Where(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State)).ToList(); + + ct.ThrowIfCancellationRequested(); + + // From here the deletion goes to the end: a half-done deletion is worse than a late one. + var none = CancellationToken.None; + await journal.AppendDeletedAsync(folder, account, stored.Entry, present.Select(m => m.RelativePath!).ToList(), mode == DeletionMode.Remember, none) + .ConfigureAwait(false); + + if (mode == DeletionMode.Remember) + { + await storage.Entries.MarkDeletedAsync(entryId, clock.Now, none).ConfigureAwait(false); + } + else + { + await storage.Entries.RemoveAsync(entryId, none).ConfigureAwait(false); + } + + foreach (var media in stored.Media) + { + hashIndex?.Remove(media.Id); + } + + var deleted = new List(); + var missing = new List(); + var failed = new List(); + foreach (var media in present) + { + var relative = media.RelativePath!; + try + { + var path = LibraryLayout.FullPath(folder, relative); + if (File.Exists(path)) + { + File.Delete(path); + deleted.Add(relative); + } + else + { + missing.Add(relative); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + failed.Add($"{relative}: {ex.Message}"); + } + } + + if (thumbnails is not null) + { + foreach (var sha in stored.Media.Select(m => m.Sha256).OfType().Distinct(StringComparer.Ordinal)) + { + var users = await storage.Media.FindBySha256Async(sha, none).ConfigureAwait(false); + if (!users.Any(u => EntryStateRules.IsPresent(u.Media.State))) + { + try + { + thumbnails.Delete(sha); + } + catch (IOException) + { + // A thumbnail left behind costs a few kilobytes; it is regenerated or ignored. + } + } + } + } + + return new DeletionResult(entryId, true, deleted, missing, failed); + } + + /// Multiple selection: deletes each entry in turn. + public async Task> DeleteManyAsync(IEnumerable entryIds, DeletionMode mode = DeletionMode.Remember, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(entryIds); + var results = new List(); + foreach (var id in entryIds.Distinct()) + { + ct.ThrowIfCancellationRequested(); + results.Add(await DeleteAsync(id, mode, ct).ConfigureAwait(false)); + } + + return results; + } +} diff --git a/src/Febe.Core/Library/LibraryIngest.cs b/src/Febe.Core/Library/LibraryIngest.cs new file mode 100644 index 0000000..c7c433d --- /dev/null +++ b/src/Febe.Core/Library/LibraryIngest.cs @@ -0,0 +1,220 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Library; + +/// The content of one file to store, as received (download) or read (import). +public sealed record MediaContent +{ + public required Stream Content { get; init; } + + /// File extension, e.g. ".jpg" or ".mp4" (from the content type or the address). + public required string Extension { get; init; } + + /// For videos: the cover image given by the page, used for the thumbnail. + public Stream? Cover { get; init; } + + /// Drop the file beyond this size («Salta i video oltre», spec §4.4). + public long? MaxBytes { get; init; } +} + +public enum MediaSaveOutcome +{ + /// The file is in the library and its record is updated. + Stored, + + /// + /// Identical (same SHA-256) to a file already present in the same account: discarded before entering the library + /// (spec §9.5). The record is not touched: the caller merges the Instagram data into the existing entry. + /// + IdenticalInAccount, +} + +/// What did. +/// Stored or discarded. +/// The stored file, when stored. +/// The file already present, when discarded. +/// Probable duplicates recorded for Alberto (same account, close perceptual hash). +public sealed record MediaSaveResult(MediaSaveOutcome Outcome, StoredFile? File, MediaLocation? Identical, IReadOnlyList SimilarPairs); + +/// +/// Puts files into the library the same way for every source (downloads of M2, imports of M7): name from the scheme +/// (§4.7), safe write with SHA-256 (§6.5), modification time = publication time, perceptual hash, thumbnail (§8.4), +/// database update, probable duplicates (§9.5) and the _febe.jsonl line (§8.5). +/// It never replaces or deletes a library file (rule 12): identical content is discarded, similar content is kept and +/// paired for Alberto's decision. +/// +public sealed class LibraryIngest( + IFebeStorage storage, + LibraryLayout layout, + LibraryNaming naming, + AccountJournal journal, + IClock clock, + ThumbnailStore? thumbnails = null, + PerceptualHashIndex? hashIndex = null, + bool setFileTimeToPublication = true, + SafeFileWriter? writer = null) +{ + private readonly SafeFileWriter _writer = writer ?? new SafeFileWriter(layout.MaxPathLength); + + /// + /// Stores one file of an entry already recorded in the database ( must have its key). + /// + /// Owner of the entry. + /// The entry. + /// The file record to fill. + /// The bytes and their extension. + /// For highlight items: the collection title ({raccolta}). + /// Cancellation: an interrupted save leaves nothing behind. + /// + /// The content exceeded : nothing was written; the caller marks the file + /// with . + /// + /// Writing failed (disk full, connection cut): nothing was written under the final name. + public async Task SaveMediaAsync( + Account account, + Entry entry, + Media media, + MediaContent content, + string? highlightTitle = null, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(media); + ArgumentNullException.ThrowIfNull(content); + if (media.Id <= 0 || media.EntryId != entry.Id || entry.AccountId != account.Id) + { + throw new ArgumentException("Il file deve appartenere all'elemento e l'elemento all'account, già registrati nel database.", nameof(media)); + } + + 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 directory = provisional.Contains('/', StringComparison.Ordinal) ? provisional[..provisional.LastIndexOf('/')] : string.Empty; + + MediaLocation? identical = null; + var saved = await _writer.SaveAsync( + content.Content, + folder, + directory, + async (digest, token) => + { + 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 + : layout.RelativePathFor(folder, scheme, NamingValues.For(account.Username, entry, media.Position, content.Extension, highlightTitle, digest.Sha256), zone); + }, + new SafeWriteOptions + { + LastWriteTime = setFileTimeToPublication ? entry.PublishedAt : null, + MaxBytes = content.MaxBytes, + }, + ct).ConfigureAwait(false); + + if (saved is null) + { + return new MediaSaveResult(MediaSaveOutcome.IdenticalInAccount, null, identical, []); + } + + ulong? hash = null; + int? width = media.Width, height = media.Height; + var hasThumbnail = false; + if (media.Kind == MediaKind.Photo) + { + hash = PerceptualHash.ComputeFromFile(saved.FullPath); + await using (var stream = File.OpenRead(saved.FullPath)) + { + if (ImageDecoding.ReadSize(stream) is { } size) + { + (width, height) = size; + } + } + + hasThumbnail = TryThumbnail(saved.Sha256, () => File.OpenRead(saved.FullPath), owned: true); + } + else if (content.Cover is { } cover) + { + hasThumbnail = TryThumbnail(saved.Sha256, () => cover, owned: false); + } + + var stored = new StoredFile(saved.RelativePath, saved.Bytes, saved.Sha256, hash, width, height, media.Duration, hasThumbnail); + var state = entry.Provenance == Provenance.Imported ? MediaState.Imported : MediaState.Downloaded; + var now = clock.Now; + await storage.Media.MarkStoredAsync(media.Id, stored, state, now, CancellationToken.None).ConfigureAwait(false); + + var pairs = new List(); + if (hash is { } h && hashIndex is not null) + { + foreach (var match in hashIndex.FindSimilar(h, PerceptualHash.DuplicateThreshold, account.Id, media.Id).Where(m => m.AccountId == account.Id)) + { + pairs.Add(await storage.Duplicates.AddAsync( + new DuplicatePair + { + Origin = DuplicateOrigin.Download, + Reason = DuplicateReason.VisuallySimilar, + ExistingMediaId = match.MediaId, + CandidateMediaId = media.Id, + Distance = match.Distance, + CreatedAt = now, + }, + CancellationToken.None).ConfigureAwait(false)); + } + + hashIndex.Add(media.Id, account.Id, h); + } + + return new MediaSaveResult(MediaSaveOutcome.Stored, stored, null, pairs); + } + + /// + /// Appends the _febe.jsonl line of an entry with its files present and its highlight collections. + /// Call it once the files of the entry are saved (and again if more files arrive later: the last line wins). + /// + public async Task AppendJournalAsync(long entryId, CancellationToken ct = default) + { + var stored = await storage.Entries.GetWithMediaAsync(entryId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Elemento {entryId} non trovato."); + var account = await storage.Accounts.GetAsync(stored.Entry.AccountId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Account {stored.Entry.AccountId} non trovato."); + var highlights = await storage.Highlights.ListForEntryAsync(entryId, ct).ConfigureAwait(false); + await journal.AppendSavedAsync( + layout.AccountFolder(account), + account, + stored.Entry, + stored.Media, + highlights.Select(h => new JournalHighlight(h.InstagramId, h.Title, h.Position)).ToList(), + ct).ConfigureAwait(false); + } + + private bool TryThumbnail(string key, Func open, bool owned) + { + if (thumbnails is null) + { + return false; + } + + try + { + var stream = open(); + try + { + return thumbnails.Create(key, stream); + } + finally + { + if (owned) + { + stream.Dispose(); + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException) + { + return false; // a missing thumbnail shows the neutral tile; the file itself is safe + } + } +} diff --git a/src/Febe.Core/Library/LibraryLayout.cs b/src/Febe.Core/Library/LibraryLayout.cs new file mode 100644 index 0000000..dc04ce8 --- /dev/null +++ b/src/Febe.Core/Library/LibraryLayout.cs @@ -0,0 +1,133 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Library; + +/// +/// Where things live in the library (spec §4.7, §8.2): one folder per account, file paths relative to it. +/// Relative paths are stored with '/' separators and converted to the platform separator here. +/// +public sealed class LibraryLayout +{ + public LibraryLayout(string libraryRoot, int maxPathLength = WindowsFileNames.MaxPathLength) + { + ArgumentException.ThrowIfNullOrWhiteSpace(libraryRoot); + Root = Path.GetFullPath(libraryRoot); + MaxPathLength = maxPathLength; + } + + /// Full path of the library folder. + public string Root { get; } + + public int MaxPathLength { get; } + + /// + /// Folder of an account: when absolute; relative to the library when relative; + /// otherwise <Libreria>/<username> (spec §4.4). + /// + public string AccountFolder(Account account) + { + ArgumentNullException.ThrowIfNull(account); + return AccountFolder(account.Folder, account.Username); + } + + public string AccountFolder(string? folder, string username) + { + if (!string.IsNullOrWhiteSpace(folder)) + { + return Path.IsPathFullyQualified(folder) + ? Path.GetFullPath(folder) + : Path.GetFullPath(Path.Combine(Root, ToPlatform(folder))); + } + + return Path.Combine(Root, WindowsFileNames.SanitizeSegment(username)); + } + + /// + /// The value to store in for a folder chosen or found on disk: null for the default + /// folder of that user name, a relative path inside the library, an absolute path outside. + /// + public string? FolderSetting(string folder, string username) + { + ArgumentException.ThrowIfNullOrWhiteSpace(folder); + var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder)); + if (PathsEqual(full, Path.Combine(Root, WindowsFileNames.SanitizeSegment(username)))) + { + return null; + } + + var relative = Path.GetRelativePath(Root, full); + return relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathFullyQualified(relative) + ? full + : relative.Replace(Path.DirectorySeparatorChar, '/'); + } + + /// Full path of a file of an account from its stored relative path. + public string FullPath(Account account, string relativePath) => FullPath(AccountFolder(account), relativePath); + + public static string FullPath(string accountFolder, string relativePath) + { + ArgumentNullException.ThrowIfNull(accountFolder); + ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); + var full = Path.GetFullPath(Path.Combine(accountFolder, ToPlatform(relativePath))); + var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(accountFolder)) + Path.DirectorySeparatorChar; + if (!full.StartsWith(root, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) + { + throw new ArgumentException("Il percorso esce dalla cartella dell'account.", nameof(relativePath)); + } + + return full; + } + + /// + /// The relative path (with '/') of a new file, rendered with the naming scheme and fitted to the path length limit + /// inside the account folder. + /// + public string RelativePathFor(string accountFolder, NamingScheme scheme, NamingValues values, TimeZoneInfo zone) + { + ArgumentNullException.ThrowIfNull(scheme); + var segments = scheme.Render(values, zone); + return string.Join('/', WindowsFileNames.FitPath(accountFolder, segments, MaxPathLength)); + } + + /// '/'-separated relative path → platform separators. + public static string ToPlatform(string relativePath) => + relativePath.Replace('\\', '/').Replace('/', Path.DirectorySeparatorChar); + + /// Platform relative path → '/'-separated (the stored form). + public static string ToStored(string relativePath) => relativePath.Replace('\\', '/'); + + private static bool PathsEqual(string a, string b) => string.Equals( + Path.TrimEndingDirectorySeparator(a), + Path.TrimEndingDirectorySeparator(b), + OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); +} + +/// The Data folder (spec §8.2): database, browser profile, thumbnails, backups, logs. +public sealed record DataFolderLayout +{ + public DataFolderLayout(string root) + { + ArgumentException.ThrowIfNullOrWhiteSpace(root); + Root = Path.GetFullPath(root); + } + + public string Root { get; } + + /// Dati/febe.sqlite. + public string Database => Path.Combine(Root, "febe.sqlite"); + + /// Dati/browser: holds the Instagram session. + public string BrowserProfile => Path.Combine(Root, "browser"); + + /// Dati/miniature. + public string Thumbnails => Path.Combine(Root, "miniature"); + + /// Dati/copie: daily database backups. + public string Backups => Path.Combine(Root, "copie"); + + /// Dati/registro: rotating logs. + public string Logs => Path.Combine(Root, "registro"); + + /// Dati/segnali.json. + public string SignalsFile => Path.Combine(Root, "segnali.json"); +} diff --git a/src/Febe.Core/Library/LibraryRebuilder.cs b/src/Febe.Core/Library/LibraryRebuilder.cs new file mode 100644 index 0000000..90afcea --- /dev/null +++ b/src/Febe.Core/Library/LibraryRebuilder.cs @@ -0,0 +1,623 @@ +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, + }; + } +} diff --git a/src/Febe.Core/Library/LibrarySettings.cs b/src/Febe.Core/Library/LibrarySettings.cs new file mode 100644 index 0000000..5ecba6e --- /dev/null +++ b/src/Febe.Core/Library/LibrarySettings.cs @@ -0,0 +1,44 @@ +using Febe.Core.Storage; + +namespace Febe.Core.Library; + +/// +/// Settings of the library (spec §4.7, mockup 08): the library folder, the two naming schemes and whether the file +/// modification time is set to the publication time. Stored in the setting table. +/// +public sealed record LibrarySettings(string LibraryRoot, LibraryNaming Naming, bool SetFileTimeToPublication = true) +{ + /// + /// Loads the settings. Missing values take the defaults; a stored scheme that is no longer valid falls back to the + /// default scheme (the settings screen shows the error when it is edited). + /// + public static async Task LoadAsync(ISettingsStore store, string defaultLibraryRoot, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(store); + ArgumentException.ThrowIfNullOrWhiteSpace(defaultLibraryRoot); + var values = await store.GetAllAsync(ct).ConfigureAwait(false); + var root = values.GetValueOrDefault(SettingKeys.LibraryRoot); + var general = NamingScheme.Validate(values.GetValueOrDefault(SettingKeys.NamingScheme) ?? NamingScheme.DefaultGeneral, forHighlights: false); + var highlight = NamingScheme.Validate(values.GetValueOrDefault(SettingKeys.HighlightNamingScheme) ?? NamingScheme.DefaultHighlight, forHighlights: true); + var setTime = !values.TryGetValue(SettingKeys.SetFileTimeToPublication, out var text) || !bool.TryParse(text, out var parsed) || parsed; + return new LibrarySettings( + string.IsNullOrWhiteSpace(root) ? defaultLibraryRoot : root, + new LibraryNaming(general.Scheme ?? NamingScheme.General, highlight.Scheme ?? NamingScheme.Highlight), + setTime); + } + + /// Stores the settings in one transaction. + public Task SaveAsync(ISettingsStore store, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(store); + return store.SetManyAsync( + new Dictionary + { + [SettingKeys.LibraryRoot] = LibraryRoot, + [SettingKeys.NamingScheme] = Naming.General.Text, + [SettingKeys.HighlightNamingScheme] = Naming.Highlight.Text, + [SettingKeys.SetFileTimeToPublication] = SetFileTimeToPublication ? "true" : "false", + }, + ct); + } +} diff --git a/src/Febe.Core/Library/NamingPreview.cs b/src/Febe.Core/Library/NamingPreview.cs new file mode 100644 index 0000000..b1e54f3 --- /dev/null +++ b/src/Febe.Core/Library/NamingPreview.cs @@ -0,0 +1,78 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Library; + +/// A file of the preview tree. +public sealed record NamingPreviewFile(string Name, MediaKind Kind); + +/// A folder of the preview tree: its path below the account folder and the files in it. +public sealed record NamingPreviewFolder(IReadOnlyList Path, IReadOnlyList Files); + +/// +/// The «Risultato» tree of the settings screen (mockup 08): an account folder with sample files rendered by the two +/// schemes. The interface shows each folder path joined by « \ ». +/// +public sealed record NamingPreview( + string AccountFolder, + IReadOnlyList Folders, + IReadOnlyList Errors, + IReadOnlyList Warnings) +{ + public bool IsValid => Errors.Count == 0; + + /// + /// Renders three sample files — a post photo (second of a series), a story video and a highlight photo — with the + /// given schemes. Sample times are local times in , so the preview reads the same anywhere. + /// + public static NamingPreview Build(string? generalScheme, string? highlightScheme, TimeZoneInfo zone, string sampleAccount = "nome.utente") + { + ArgumentNullException.ThrowIfNull(zone); + ArgumentException.ThrowIfNullOrWhiteSpace(sampleAccount); + var general = NamingScheme.Validate(generalScheme, forHighlights: false); + var highlight = NamingScheme.Validate(highlightScheme, forHighlights: true); + var errors = general.Errors.Select(e => "Schema: " + e) + .Concat(highlight.Errors.Select(e => "Schema per le raccolte in evidenza: " + e)) + .ToList(); + var warnings = general.Warnings.Select(e => "Schema: " + e) + .Concat(highlight.Warnings.Select(e => "Schema per le raccolte in evidenza: " + e)) + .ToList(); + + var folders = new List(); + void Add(NamingScheme scheme, EntryKind kind, DateTime local, string code, int n, MediaKind media, string? collection) + { + var values = new NamingValues( + sampleAccount, + kind, + LocalCalendar.FromLocal(local, zone), + code, + n, + media == MediaKind.Video ? ".mp4" : ".jpg", + collection); + var segments = scheme.Render(values, zone); + var path = segments.Take(segments.Count - 1).ToList(); + var file = new NamingPreviewFile(segments[^1], media); + var existing = folders.FindIndex(f => f.Path.SequenceEqual(path, StringComparer.Ordinal)); + if (existing >= 0) + { + folders[existing] = folders[existing] with { Files = [.. folders[existing].Files, file] }; + } + else + { + folders.Add(new NamingPreviewFolder(path, [file])); + } + } + + if (general.Scheme is { } g) + { + Add(g, EntryKind.Post, new DateTime(2026, 10, 10, 18, 22, 5), "DBx3kQ2", 2, MediaKind.Photo, null); + Add(g, EntryKind.Story, new DateTime(2026, 10, 13, 9, 41, 7), "3742118", 1, MediaKind.Video, null); + } + + if (highlight.Scheme is { } h) + { + Add(h, EntryKind.Highlight, new DateTime(2025, 8, 2, 10, 11, 12), "3391207", 1, MediaKind.Photo, "Estate 2025"); + } + + return new NamingPreview(WindowsFileNames.SanitizeSegment(sampleAccount), folders, errors, warnings); + } +} diff --git a/src/Febe.Core/Library/NamingScheme.cs b/src/Febe.Core/Library/NamingScheme.cs new file mode 100644 index 0000000..d46d77b --- /dev/null +++ b/src/Febe.Core/Library/NamingScheme.cs @@ -0,0 +1,282 @@ +using System.Globalization; +using System.Text; +using Febe.Core.Domain; + +namespace Febe.Core.Library; + +/// +/// A naming scheme of the library (spec §4.7), e.g. {account}\{tipo}\{anno}\{data}_{ora}_{codice}_{n}. +/// +/// A backslash (or a slash) separates folders on every operating system. Placeholders: account, tipo, +/// anno, mese, data, ora, codice, n, raccolta (only in the scheme of +/// highlight collections). Dates and times are in Alberto's time zone: data is yyyy-MM-dd and ora is +/// HH-mm-ss. The file extension is added to the last segment. +/// +/// +/// The scheme is rendered inside the folder of the account: when it starts with the segment {account}, that +/// segment is the account folder (which may be elsewhere, spec §4.4) and is not repeated. +/// +/// +public sealed class NamingScheme +{ + public const string DefaultGeneral = @"{account}\{tipo}\{anno}\{data}_{ora}_{codice}_{n}"; + + public const string DefaultHighlight = @"{account}\evidenza\{raccolta}\{data}_{ora}_{codice}_{n}"; + + /// Placeholders accepted, in the order shown in the interface. + public static IReadOnlyList Placeholders { get; } = ["account", "tipo", "anno", "mese", "data", "ora", "codice", "n", "raccolta"]; + + private readonly IReadOnlyList> _segments; + + private NamingScheme(string text, bool forHighlights, IReadOnlyList> segments) + { + Text = text; + ForHighlights = forHighlights; + _segments = segments; + } + + /// The scheme as written. + public string Text { get; } + + /// True for the scheme of highlight collections (accepts {raccolta}). + public bool ForHighlights { get; } + + public static NamingScheme General { get; } = Parse(DefaultGeneral, forHighlights: false); + + public static NamingScheme Highlight { get; } = Parse(DefaultHighlight, forHighlights: true); + + /// Parses a scheme. + /// The scheme is not valid; the message (Italian) says why. + public static NamingScheme Parse(string text, bool forHighlights) + { + var validation = Validate(text, forHighlights); + if (!validation.IsValid) + { + throw new FormatException(validation.Errors[0]); + } + + return validation.Scheme!; + } + + /// Checks a scheme for the settings screen: errors block saving, warnings are shown. + public static NamingSchemeValidation Validate(string? text, bool forHighlights) + { + var errors = new List(); + var warnings = new List(); + if (string.IsNullOrWhiteSpace(text)) + { + return new NamingSchemeValidation(null, ["Lo schema è vuoto."], []); + } + + var rawSegments = text.Trim().Split(['\\', '/']); + var segments = new List>(); + var used = new HashSet(StringComparer.Ordinal); + for (var i = 0; i < rawSegments.Length; i++) + { + var raw = rawSegments[i]; + if (raw.Trim().Length == 0) + { + errors.Add(i == rawSegments.Length - 1 + ? "Lo schema finisce con una barra: manca il nome del file." + : "Lo schema contiene due barre di seguito o comincia con una barra."); + continue; + } + + var tokens = Tokenize(raw, errors); + foreach (var token in tokens.Where(t => t.IsPlaceholder)) + { + used.Add(token.Value); + if (!Placeholders.Contains(token.Value)) + { + errors.Add($"Segnaposto sconosciuto: {{{token.Value}}}. Quelli ammessi sono: {string.Join(", ", Placeholders)}."); + } + else if (token.Value == "raccolta" && !forHighlights) + { + errors.Add("{raccolta} si usa solo nello schema per le raccolte in evidenza."); + } + } + + segments.Add(tokens); + } + + if (errors.Count > 0) + { + return new NamingSchemeValidation(null, errors.Distinct().ToList(), []); + } + + // The account folder segment is implicit: drop a leading «{account}». + if (segments.Count > 1 && segments[0] is [{ IsPlaceholder: true, Value: "account" }]) + { + segments.RemoveAt(0); + } + + if (!used.Contains("codice") && !used.Contains("n")) + { + warnings.Add("Senza {codice} e {n} più file possono avere lo stesso nome: Febe aggiunge un numero per distinguerli."); + } + else if (!used.Contains("n")) + { + warnings.Add("Senza {n} i file di un post con più foto o video hanno lo stesso nome: Febe aggiunge un numero per distinguerli."); + } + + if (forHighlights && !used.Contains("raccolta")) + { + warnings.Add("Senza {raccolta} i contenuti delle diverse raccolte finiscono nella stessa cartella."); + } + + return new NamingSchemeValidation(new NamingScheme(text.Trim(), forHighlights, segments), [], warnings); + } + + /// + /// Renders the path of a file relative to the account folder, as sanitized segments (the last one is the file name + /// with its extension). Use or to apply the + /// length limit. + /// + public IReadOnlyList Render(NamingValues values, TimeZoneInfo zone) + { + ArgumentNullException.ThrowIfNull(values); + ArgumentNullException.ThrowIfNull(zone); + var local = LocalCalendar.ToLocal(values.PublishedAt, zone); + var result = new List(_segments.Count); + for (var i = 0; i < _segments.Count; i++) + { + var builder = new StringBuilder(); + foreach (var token in _segments[i]) + { + builder.Append(token.IsPlaceholder ? Value(token.Value, values, local) : token.Value); + } + + if (i == _segments.Count - 1) + { + builder.Append(NormalizeExtension(values.Extension)); + } + + result.Add(WindowsFileNames.SanitizeSegment(builder.ToString())); + } + + return result; + } + + /// Renders the path relative to the account folder with '/' separators (the form stored in the database). + public string RenderRelativePath(NamingValues values, TimeZoneInfo zone) => string.Join('/', Render(values, zone)); + + public override string ToString() => Text; + + private static string Value(string placeholder, NamingValues values, DateTime local) => placeholder switch + { + "account" => values.Account, + "tipo" => EntryKindNames.Folder(values.Kind), + "anno" => local.ToString("yyyy", CultureInfo.InvariantCulture), + "mese" => local.ToString("MM", CultureInfo.InvariantCulture), + "data" => local.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "ora" => local.ToString("HH-mm-ss", CultureInfo.InvariantCulture), + "codice" => values.Code, + "n" => values.Position.ToString(CultureInfo.InvariantCulture), + "raccolta" => string.IsNullOrWhiteSpace(values.Collection) ? "senza titolo" : values.Collection, + _ => throw new InvalidOperationException(placeholder), + }; + + private static string NormalizeExtension(string? extension) + { + if (string.IsNullOrWhiteSpace(extension)) + { + return string.Empty; + } + + var trimmed = extension.Trim().ToLowerInvariant(); + return trimmed.StartsWith('.') ? trimmed : "." + trimmed; + } + + private static List Tokenize(string segment, List errors) + { + var tokens = new List(); + var literal = new StringBuilder(); + for (var i = 0; i < segment.Length; i++) + { + var ch = segment[i]; + if (ch == '{') + { + var close = segment.IndexOf('}', i + 1); + if (close < 0) + { + errors.Add("Una parentesi graffa aperta non è chiusa."); + return tokens; + } + + if (literal.Length > 0) + { + tokens.Add(new Token(false, literal.ToString())); + literal.Clear(); + } + + var name = segment[(i + 1)..close].Trim().ToLowerInvariant(); + if (name.Length == 0 || name.Contains('{', StringComparison.Ordinal)) + { + errors.Add("Un segnaposto è vuoto o contiene una graffa."); + return tokens; + } + + tokens.Add(new Token(true, name)); + i = close; + } + else if (ch == '}') + { + errors.Add("Una parentesi graffa chiusa non ha la sua apertura."); + return tokens; + } + else + { + literal.Append(ch); + } + } + + if (literal.Length > 0) + { + tokens.Add(new Token(false, literal.ToString())); + } + + return tokens; + } + + private readonly record struct Token(bool IsPlaceholder, string Value); +} + +/// Result of . +public sealed record NamingSchemeValidation(NamingScheme? Scheme, IReadOnlyList Errors, IReadOnlyList Warnings) +{ + public bool IsValid => Scheme is not null && Errors.Count == 0; +} + +/// Values of the placeholders for one file. +/// User name of the account ({account}). +/// Kind of the entry ({tipo}). +/// Publication time; rendered in Alberto's zone. +/// The {codice} value: see . +/// Position of the file in the entry, from 1 ({n}). +/// File extension, with or without the dot (e.g. ".jpg"). +/// Title of the highlight collection ({raccolta}). +public sealed record NamingValues( + string Account, + EntryKind Kind, + DateTimeOffset PublishedAt, + string Code, + int Position, + string Extension, + string? Collection = null) +{ + /// Values for a file of an entry. + public static NamingValues For(string account, Entry entry, int position, string extension, string? collection = null, string? sha256 = null) + { + ArgumentNullException.ThrowIfNull(entry); + return new NamingValues(account, entry.Kind, entry.PublishedAt, entry.NameCode(sha256), position, extension, collection); + } +} + +/// The two configurable schemes (spec §4.7): general and for highlight collections. +public sealed record LibraryNaming(NamingScheme General, NamingScheme Highlight) +{ + public static LibraryNaming Default { get; } = new(NamingScheme.General, NamingScheme.Highlight); + + /// The scheme that applies to an entry kind. + public NamingScheme For(EntryKind kind) => kind == EntryKind.Highlight ? Highlight : General; +} diff --git a/src/Febe.Core/Library/PerceptualHash.cs b/src/Febe.Core/Library/PerceptualHash.cs new file mode 100644 index 0000000..63b88f5 --- /dev/null +++ b/src/Febe.Core/Library/PerceptualHash.cs @@ -0,0 +1,235 @@ +using System.Numerics; +using SkiaSharp; + +namespace Febe.Core.Library; + +/// +/// 64-bit perceptual hash of photos (spec §8.4, «impronta visiva»): the classic DCT pHash. +/// +/// the image is decoded upright and reduced to 32×32 grey levels by area averaging (aspect ratio is not kept: +/// resizing does not change the hash); +/// a 2-D DCT-II is computed and the 8×8 lowest frequencies are kept; +/// each of the 64 coefficients gives a bit: 1 when above the median of the 64. +/// +/// Two photos are probable duplicates when the Hamming distance of their hashes is at most +/// . Videos have no perceptual hash: for them only SHA-256 counts (spec §9.3). +/// +public static class PerceptualHash +{ + /// + /// Maximum Hamming distance (out of 64 bits) for two photos to be probable duplicates. + /// + /// Calibrated on 2026-10-13 by Febe.Tests.Library.PerceptualHashTests on 24 generated scenes (gradients, + /// shapes, lines and grain; 1200×900 and 900×1200), each compared with its variants: + /// + /// resized to 50%, 25%, 8% (96 px) and 150%, recompressed as JPEG at quality 95, 70, 40 and 20, resized to a + /// third and recompressed twice, saved as PNG: largest distance 4 (only the 96-px reduction; all others ≤ 2); + /// cropped — central 80%, 75% and 60% of each side, one side cut by 10% or 25%, top third removed, square and + /// 4:5 crops, a corner quarter: smallest distance 8; + /// different scenes: smallest distance 20 (average 31). + /// + /// Every hash has exactly 32 bits set (median split), so distances are always even: 6 sits in the middle of the + /// gap between 4 and 8. A very light crop (5% on every side) measured 6–18 and may be proposed as a duplicate: + /// the pair is only shown to Alberto, never resolved automatically (rule 12). + /// + /// + public const int DuplicateThreshold = 6; + + private const int Size = 32; + private const int Low = 8; + + private static readonly double[,] Cosines = BuildCosines(); + + /// Hamming distance between two hashes (0–64). + public static int Distance(ulong a, ulong b) => BitOperations.PopCount(a ^ b); + + /// True when two hashes are within . + public static bool AreSimilar(ulong a, ulong b, int threshold = DuplicateThreshold) => Distance(a, b) <= threshold; + + /// Hash of an encoded image; null when the content is not a decodable image. + public static ulong? Compute(Stream encodedImage) + { + ArgumentNullException.ThrowIfNull(encodedImage); + using var bitmap = ImageDecoding.DecodeUpright(encodedImage, minLongSide: 256); + return bitmap is null ? null : Compute(bitmap); + } + + /// Hash of an image file; null when it is not a decodable image. + public static ulong? ComputeFromFile(string path) + { + using var stream = File.OpenRead(path); + return Compute(stream); + } + + /// Hash of a decoded bitmap (any size, premultiplied RGBA 8888 or convertible). + internal static ulong Compute(SKBitmap bitmap) + { + ArgumentNullException.ThrowIfNull(bitmap); + using var rgba = bitmap.ColorType == SKColorType.Rgba8888 && bitmap.AlphaType == SKAlphaType.Premul + ? null + : bitmap.Copy(SKColorType.Rgba8888); + var source = rgba ?? bitmap; + var grey = Luminance(source); + var small = AreaResample(grey, source.Width, source.Height, Size, Size); + return HashOf(small); + } + + /// The hash of a 32×32 grey image (row-major). + internal static ulong HashOf(double[] pixels) + { + // Separable DCT-II, only the 8 lowest frequencies in each direction. + var rows = new double[Size * Low]; + for (var y = 0; y < Size; y++) + { + for (var u = 0; u < Low; u++) + { + double sum = 0; + for (var x = 0; x < Size; x++) + { + sum += pixels[(y * Size) + x] * Cosines[u, x]; + } + + rows[(y * Low) + u] = sum; + } + } + + var coefficients = new double[Low * Low]; + for (var v = 0; v < Low; v++) + { + for (var u = 0; u < Low; u++) + { + double sum = 0; + for (var y = 0; y < Size; y++) + { + sum += rows[(y * Low) + u] * Cosines[v, y]; + } + + coefficients[(v * Low) + u] = sum; + } + } + + var sorted = (double[])coefficients.Clone(); + Array.Sort(sorted); + var median = (sorted[31] + sorted[32]) / 2; + ulong hash = 0; + for (var i = 0; i < coefficients.Length; i++) + { + if (coefficients[i] > median) + { + hash |= 1UL << i; + } + } + + return hash; + } + + /// Grey levels (0–255) of an RGBA premultiplied bitmap, composited over white. + private static double[] Luminance(SKBitmap bitmap) + { + var width = bitmap.Width; + var height = bitmap.Height; + var result = new double[width * height]; + var pixels = bitmap.GetPixelSpan(); + var rowBytes = bitmap.RowBytes; + for (var y = 0; y < height; y++) + { + var row = pixels.Slice(y * rowBytes, width * 4); + for (var x = 0; x < width; x++) + { + var r = row[x * 4]; + var g = row[(x * 4) + 1]; + var b = row[(x * 4) + 2]; + var a = row[(x * 4) + 3]; + var white = 255 - a; // premultiplied: over white, each channel gains (255 − alpha) + result[(y * width) + x] = (0.299 * (r + white)) + (0.587 * (g + white)) + (0.114 * (b + white)); + } + } + + return result; + } + + /// Area-averaging resample with exact fractional coverage (no aliasing when reducing). + internal static double[] AreaResample(double[] source, int sw, int sh, int dw, int dh) + { + var horizontal = new double[dw * sh]; + var xs = Weights(sw, dw); + for (var y = 0; y < sh; y++) + { + for (var dx = 0; dx < dw; dx++) + { + double sum = 0; + foreach (var (index, weight) in xs[dx]) + { + sum += source[(y * sw) + index] * weight; + } + + horizontal[(y * dw) + dx] = sum; + } + } + + var result = new double[dw * dh]; + var ys = Weights(sh, dh); + for (var dy = 0; dy < dh; dy++) + { + for (var dx = 0; dx < dw; dx++) + { + double sum = 0; + foreach (var (index, weight) in ys[dy]) + { + sum += horizontal[(index * dw) + dx] * weight; + } + + result[(dy * dw) + dx] = sum; + } + } + + return result; + } + + /// For each target cell, the source cells it covers and their normalized weights. + private static List<(int Index, double Weight)>[] Weights(int sourceLength, int targetLength) + { + var scale = (double)sourceLength / targetLength; + var weights = new List<(int, double)>[targetLength]; + for (var t = 0; t < targetLength; t++) + { + var start = t * scale; + var end = start + scale; + var list = new List<(int, double)>(); + if (scale <= 1) + { + // Enlarging: nearest source cell by centre. + list.Add((Math.Min(sourceLength - 1, (int)((t + 0.5) * scale)), 1.0)); + } + else + { + for (var s = (int)Math.Floor(start); s < Math.Ceiling(end) && s < sourceLength; s++) + { + var overlap = Math.Min(end, s + 1) - Math.Max(start, s); + if (overlap > 0) + { + list.Add((s, overlap / scale)); + } + } + } + + weights[t] = list; + } + + return weights; + } + + private static double[,] BuildCosines() + { + var table = new double[Low, Size]; + for (var u = 0; u < Low; u++) + { + for (var x = 0; x < Size; x++) + { + table[u, x] = Math.Cos(((2 * x) + 1) * u * Math.PI / (2 * Size)); + } + } + + return table; + } +} diff --git a/src/Febe.Core/Library/PerceptualHashIndex.cs b/src/Febe.Core/Library/PerceptualHashIndex.cs new file mode 100644 index 0000000..f47660b --- /dev/null +++ b/src/Febe.Core/Library/PerceptualHashIndex.cs @@ -0,0 +1,164 @@ +using System.Numerics; +using Febe.Core.Storage; + +namespace Febe.Core.Library; + +/// A library photo close to the searched one. +public readonly record struct PerceptualHashMatch(long MediaId, long AccountId, ulong Hash, int Distance); + +/// +/// In-memory index of the perceptual hashes of the library (spec §8.4: «le impronte stanno in memoria: il confronto di +/// una foto con 200.000 è questione di millisecondi»). A linear scan over contiguous arrays with a hardware popcount: +/// about a nanosecond per comparison, no tree to keep balanced. Thread-safe. +/// +public sealed class PerceptualHashIndex +{ + private readonly ReaderWriterLockSlim _lock = new(LockRecursionPolicy.NoRecursion); + private readonly Dictionary _positions = []; + private ulong[] _hashes = new ulong[1024]; + private long[] _mediaIds = new long[1024]; + private long[] _accountIds = new long[1024]; + private int _count; + + public int Count + { + get + { + _lock.EnterReadLock(); + try + { + return _count; + } + finally + { + _lock.ExitReadLock(); + } + } + } + + /// Replaces the content with the hashes stored in the database. + public void Load(IEnumerable records) + { + ArgumentNullException.ThrowIfNull(records); + _lock.EnterWriteLock(); + try + { + _positions.Clear(); + _count = 0; + foreach (var record in records) + { + AddUnlocked(record.MediaId, record.AccountId, record.Hash); + } + } + finally + { + _lock.ExitWriteLock(); + } + } + + /// Adds or replaces the hash of a file. + public void Add(long mediaId, long accountId, ulong hash) + { + _lock.EnterWriteLock(); + try + { + AddUnlocked(mediaId, accountId, hash); + } + finally + { + _lock.ExitWriteLock(); + } + } + + /// Removes the hash of a file (deleted from the library). + public bool Remove(long mediaId) + { + _lock.EnterWriteLock(); + try + { + if (!_positions.Remove(mediaId, out var index)) + { + return false; + } + + var last = _count - 1; + if (index != last) + { + _hashes[index] = _hashes[last]; + _mediaIds[index] = _mediaIds[last]; + _accountIds[index] = _accountIds[last]; + _positions[_mediaIds[index]] = index; + } + + _count--; + return true; + } + finally + { + _lock.ExitWriteLock(); + } + } + + /// + /// Files whose hash is within of . With + /// , matches of that account come first (spec §9.3: «si cerca prima nell'account di + /// destinazione, poi nel resto della libreria»); then by distance. + /// + public IReadOnlyList FindSimilar( + ulong hash, + int maxDistance = PerceptualHash.DuplicateThreshold, + long? preferAccountId = null, + long? excludeMediaId = null, + int limit = 50) + { + var matches = new List(); + _lock.EnterReadLock(); + try + { + var hashes = _hashes.AsSpan(0, _count); + for (var i = 0; i < hashes.Length; i++) + { + var distance = BitOperations.PopCount(hashes[i] ^ hash); + if (distance <= maxDistance && _mediaIds[i] != excludeMediaId) + { + matches.Add(new PerceptualHashMatch(_mediaIds[i], _accountIds[i], hashes[i], distance)); + } + } + } + finally + { + _lock.ExitReadLock(); + } + + return matches + .OrderBy(m => preferAccountId is { } a && m.AccountId == a ? 0 : 1) + .ThenBy(m => m.Distance) + .ThenBy(m => m.MediaId) + .Take(Math.Max(1, limit)) + .ToList(); + } + + private void AddUnlocked(long mediaId, long accountId, ulong hash) + { + if (_positions.TryGetValue(mediaId, out var existing)) + { + _hashes[existing] = hash; + _accountIds[existing] = accountId; + return; + } + + if (_count == _hashes.Length) + { + var size = _hashes.Length * 2; + Array.Resize(ref _hashes, size); + Array.Resize(ref _mediaIds, size); + Array.Resize(ref _accountIds, size); + } + + _hashes[_count] = hash; + _mediaIds[_count] = mediaId; + _accountIds[_count] = accountId; + _positions[mediaId] = _count; + _count++; + } +} diff --git a/src/Febe.Core/Library/SafeFileWriter.cs b/src/Febe.Core/Library/SafeFileWriter.cs new file mode 100644 index 0000000..0a04ec3 --- /dev/null +++ b/src/Febe.Core/Library/SafeFileWriter.cs @@ -0,0 +1,292 @@ +using System.Buffers; +using System.Globalization; +using System.Security.Cryptography; + +namespace Febe.Core.Library; + +/// Size and SHA-256 of a file written by . +public readonly record struct FileDigest(long Bytes, string Sha256); + +/// A file safely written to its final name. +/// Path relative to the root folder, '/' separated (may differ from the one asked: never overwrites). +/// Full path on disk. +/// Size. +/// Lowercase hex SHA-256, computed while writing. +/// The modification time was set as asked. +public sealed record SavedFile(string RelativePath, string FullPath, long Bytes, string Sha256, bool LastWriteTimeSet); + +/// Options of a safe write. +public sealed record SafeWriteOptions +{ + /// Set the file modification time to this instant (publication time, spec §4.7). Null leaves it. + public DateTimeOffset? LastWriteTime { get; init; } + + /// Abort with beyond this size (e.g. «Salta i video oltre»). + public long? MaxBytes { get; init; } + + /// Bytes written so far. + public IProgress? Progress { get; init; } +} + +/// The content exceeded ; nothing was kept. +public sealed class FileTooLargeException : IOException +{ + public FileTooLargeException() + { + } + + public FileTooLargeException(string message) + : base(message) + { + } + + public FileTooLargeException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// +/// Writes library files safely (spec §6.5 point 4, rule 12): +/// +/// the content goes to a temporary name (.febe-*.part) in the destination folder; +/// SHA-256 is computed while writing, then the data is flushed to disk; +/// the file is renamed to its final name; an existing file is never overwritten — a free name +/// («nome (2).jpg») is chosen instead; +/// if anything goes wrong or the operation is cancelled, the temporary file is removed: an interrupted +/// download never leaves a file with the final name. +/// +/// +public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathLength) +{ + /// Prefix of temporary files. + public const string TempPrefix = ".febe-"; + + /// Suffix of temporary files. + public const string TempSuffix = ".part"; + + private const int BufferSize = 128 * 1024; + private const int MaxNameAttempts = 10_000; + + /// Serializes «is the name free? then rename» across all writers of the process. + private static readonly Lock MoveGate = new(); + + /// Writes to inside . + public Task SaveAsync(Stream source, string rootFolder, string relativePath, SafeWriteOptions? options = null, CancellationToken ct = default) + { + var segments = Segments(relativePath); + var directory = string.Join('/', segments.Take(segments.Count - 1)); + var sanitized = string.Join('/', segments); + return SaveAsync(source, rootFolder, directory, _ => sanitized, options, ct); + } + + /// + /// Writes and decides the final name only after hashing (e.g. profile pictures, named after + /// their SHA-256). The temporary file is written in (relative to the root, '/' + /// separated; use the destination folder when known). + /// + public async Task SaveAsync( + Stream source, + string rootFolder, + string tempDirectory, + Func relativePathFor, + SafeWriteOptions? options = null, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(relativePathFor); + var saved = await SaveAsync(source, rootFolder, tempDirectory, (d, _) => ValueTask.FromResult(relativePathFor(d)), options, ct) + .ConfigureAwait(false); + return saved!; + } + + /// + /// Writes to a temporary file, then asks — knowing size and + /// SHA-256 — for the final relative path. When returns null the content is discarded + /// (e.g. identical to a file already in the account, spec §9.5): nothing is left on disk and the result is null. + /// + public async Task SaveAsync( + Stream source, + string rootFolder, + string tempDirectory, + Func> decide, + SafeWriteOptions? options = null, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentException.ThrowIfNullOrWhiteSpace(rootFolder); + ArgumentNullException.ThrowIfNull(decide); + options ??= new SafeWriteOptions(); + var root = Path.GetFullPath(rootFolder); + var tempFolder = string.IsNullOrEmpty(tempDirectory) ? root : LibraryLayout.FullPath(root, tempDirectory); + Directory.CreateDirectory(tempFolder); + var tempPath = Path.Combine(tempFolder, TempPrefix + Guid.NewGuid().ToString("N")[..12] + TempSuffix); + + try + { + var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false); + ct.ThrowIfCancellationRequested(); + + var desired = await decide(digest, ct).ConfigureAwait(false); + if (desired is null) + { + return null; + } + + ct.ThrowIfCancellationRequested(); + var finalPath = MoveToFreeName(tempPath, root, desired, out var relative); + var timeSet = true; + if (options.LastWriteTime is { } time) + { + try + { + File.SetLastWriteTimeUtc(finalPath, time.UtcDateTime); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentOutOfRangeException) + { + timeSet = false; // some shares refuse it: the file is still good + } + } + + return new SavedFile(relative, finalPath, digest.Bytes, digest.Sha256, timeSet); + } + finally + { + TryDelete(tempPath); // no-op after a successful move + } + } + + /// + /// Removes temporary files left by an interrupted process (never library files: only .febe-*.part). + /// Returns how many were removed. + /// + public static int CleanupTemporaryFiles(string folder, bool recursive = true) + { + if (!Directory.Exists(folder)) + { + return 0; + } + + var removed = 0; + var files = Directory.EnumerateFiles( + folder, + TempPrefix + "*" + TempSuffix, + new EnumerationOptions { RecurseSubdirectories = recursive, IgnoreInaccessible = true, AttributesToSkip = 0 }); + foreach (var file in files) + { + if (TryDelete(file)) + { + removed++; + } + } + + return removed; + } + + /// True for a temporary file name of the safe writer. + public static bool IsTemporaryFile(string path) + { + var name = Path.GetFileName(path); + return name.StartsWith(TempPrefix, StringComparison.Ordinal) && name.EndsWith(TempSuffix, StringComparison.Ordinal); + } + + private static async Task WriteTempAsync(Stream source, string tempPath, SafeWriteOptions options, CancellationToken ct) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = ArrayPool.Shared.Rent(BufferSize); + long total = 0; + try + { + await using var target = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize, FileOptions.Asynchronous); + int read; + while ((read = await source.ReadAsync(buffer.AsMemory(0, BufferSize), ct).ConfigureAwait(false)) > 0) + { + total += read; + if (options.MaxBytes is { } max && total > max) + { + throw new FileTooLargeException( + string.Create(CultureInfo.InvariantCulture, $"Il file supera il limite di {max} byte: non viene salvato.")); + } + + hash.AppendData(buffer, 0, read); + await target.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false); + options.Progress?.Report(total); + } + + await target.FlushAsync(ct).ConfigureAwait(false); + target.Flush(flushToDisk: true); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + + return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset())); + } + + /// Sanitized segments of a relative path ('/' or '\' separated). «..» becomes «_»: nothing escapes the root. + private static List Segments(string relativePath) + { + ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); + var segments = LibraryLayout.ToStored(relativePath) + .Split('/', StringSplitOptions.RemoveEmptyEntries) + .Select(WindowsFileNames.SanitizeSegment) + .ToList(); + return segments.Count == 0 ? throw new ArgumentException("Il nome del file è vuoto.", nameof(relativePath)) : segments; + } + + private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, out string relative) + { + var segments = Segments(desiredRelativePath); + var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]); + for (var attempt = 1; attempt <= MaxNameAttempts; attempt++) + { + var name = attempt == 1 ? segments[^1] : string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"); + var candidate = segments.Take(segments.Count - 1).Append(WindowsFileNames.SanitizeSegment(name)).ToList(); + var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength); + relative = string.Join('/', fitted); + var finalPath = LibraryLayout.FullPath(root, relative); + Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!); + + // On Unix File.Move(overwrite: false) checks for the destination and then renames, and a rename replaces: + // two writers of this process could overwrite each other. The check and the rename are therefore done under + // one lock (Febe is the only writer of its library). On Windows the move itself refuses an existing name. + lock (MoveGate) + { + if (File.Exists(finalPath) || Directory.Exists(finalPath)) + { + continue; + } + + try + { + File.Move(tempPath, finalPath, overwrite: false); + return finalPath; + } + catch (IOException) when (File.Exists(finalPath)) + { + // Another program took the name in the meantime: try the next one. + } + } + } + + throw new IOException($"Nessun nome libero per {desiredRelativePath} dopo {MaxNameAttempts} tentativi."); + } + + 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) + { + // Best effort: a leftover temporary file is removed at the next start-up. + } + + return false; + } +} diff --git a/src/Febe.Core/Library/TextSearch.cs b/src/Febe.Core/Library/TextSearch.cs new file mode 100644 index 0000000..9bdbfa4 --- /dev/null +++ b/src/Febe.Core/Library/TextSearch.cs @@ -0,0 +1,61 @@ +using System.Globalization; +using System.Text; + +namespace Febe.Core.Library; + +/// +/// Normalization for the search of the library (spec §4.6: account name and caption): lowercase, without accents, +/// with runs of white space collapsed. «Perché» and «perche» match. +/// +public static class TextSearch +{ + public static string Normalize(string? text) + { + if (string.IsNullOrEmpty(text)) + { + return string.Empty; + } + + var decomposed = text.Normalize(NormalizationForm.FormD); + var builder = new StringBuilder(decomposed.Length); + var lastWasSpace = false; + foreach (var ch in decomposed) + { + var category = CharUnicodeInfo.GetUnicodeCategory(ch); + if (category is UnicodeCategory.NonSpacingMark or UnicodeCategory.SpacingCombiningMark or UnicodeCategory.EnclosingMark) + { + continue; + } + + if (char.IsWhiteSpace(ch)) + { + if (!lastWasSpace && builder.Length > 0) + { + builder.Append(' '); + } + + lastWasSpace = true; + continue; + } + + lastWasSpace = false; + builder.Append(char.ToLowerInvariant(ch)); + } + + return builder.ToString().TrimEnd().Normalize(NormalizationForm.FormC); + } + + /// Text indexed for an entry: caption and author. + public static string ForEntry(string? caption, string? author) => + Normalize(string.Join(' ', new[] { caption, author }.Where(s => !string.IsNullOrWhiteSpace(s)))); + + /// A LIKE pattern «%term%» with %, _ and \ escaped (use with ESCAPE '\'). + public static string LikePattern(string normalizedTerm) + { + ArgumentNullException.ThrowIfNull(normalizedTerm); + var escaped = normalizedTerm.Replace("\\", "\\\\", StringComparison.Ordinal) + .Replace("%", "\\%", StringComparison.Ordinal) + .Replace("_", "\\_", StringComparison.Ordinal); + return "%" + escaped + "%"; + } +} diff --git a/src/Febe.Core/Library/ThumbnailStore.cs b/src/Febe.Core/Library/ThumbnailStore.cs new file mode 100644 index 0000000..1f71c89 --- /dev/null +++ b/src/Febe.Core/Library/ThumbnailStore.cs @@ -0,0 +1,176 @@ +using SkiaSharp; + +namespace Febe.Core.Library; + +/// +/// Thumbnails of the library (spec §8.4): 480 pixels on the long side, JPEG, generated once and kept under +/// Dati/miniature, in 256 shard folders named after the first two hex digits of the key. The key is the +/// SHA-256 of the library file, so identical files share one thumbnail. Videos use the cover given by the page or a +/// frame (); without either, the interface shows the neutral tile +/// (). +/// +public sealed class ThumbnailStore +{ + /// Long side of a thumbnail, in pixels. + public const int LongSide = 480; + + /// JPEG quality of thumbnails. + public const int JpegQuality = 82; + + /// File name of the neutral tile for videos without a cover. + public const string NeutralVideoTileName = "_video.jpg"; + + private readonly string _root; + + public ThumbnailStore(string thumbnailsFolder) + { + ArgumentException.ThrowIfNullOrWhiteSpace(thumbnailsFolder); + _root = Path.GetFullPath(thumbnailsFolder); + } + + /// The thumbnails folder. + public string Root => _root; + + /// Path of the thumbnail of a key (lowercase hex SHA-256). + public string PathFor(string key) + { + ValidateKey(key); + var k = key.ToLowerInvariant(); + return Path.Combine(_root, k[..2], k + ".jpg"); + } + + public bool Exists(string key) => File.Exists(PathFor(key)); + + /// + /// Creates the thumbnail of an encoded image (photo, or video cover). Does nothing when it already exists. + /// Returns false when the content cannot be decoded. + /// + public bool Create(string key, Stream encodedImage) + { + ArgumentNullException.ThrowIfNull(encodedImage); + var target = PathFor(key); + if (File.Exists(target)) + { + return true; + } + + using var bitmap = ImageDecoding.DecodeUpright(encodedImage, LongSide); + if (bitmap is null) + { + return false; + } + + WriteJpeg(target, Render(bitmap, LongSide)); + return true; + } + + /// Creates the thumbnail of an image file. + public bool CreateFromFile(string key, string imagePath) + { + using var stream = File.OpenRead(imagePath); + return Create(key, stream); + } + + /// Removes a thumbnail (when no file of the library uses its key any more). + public bool Delete(string key) + { + var path = PathFor(key); + if (!File.Exists(path)) + { + return false; + } + + File.Delete(path); + return true; + } + + /// The neutral tile for videos without a cover, created on first use (grey, with a play sign). + public string NeutralVideoTile() + { + var path = Path.Combine(_root, NeutralVideoTileName); + if (File.Exists(path)) + { + return path; + } + + const int width = 270, height = LongSide; // 9:16, like stories and reels + using var surface = SKSurface.Create(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul)); + var canvas = surface.Canvas; + canvas.Clear(new SKColor(0xE4, 0xE4, 0xE4)); + using (var paint = new SKPaint { Color = new SKColor(0x9A, 0x9A, 0x9A), IsAntialias = true, Style = SKPaintStyle.Fill }) + { + canvas.DrawCircle(width / 2f, height / 2f, 34, paint); + } + + using (var paint = new SKPaint { Color = new SKColor(0xE4, 0xE4, 0xE4), IsAntialias = true, Style = SKPaintStyle.Fill }) + { + // A play triangle drawn as three thin rectangles would be blurry; vertices keep it crisp. + var cx = width / 2f + 4; + var cy = height / 2f; + SKPoint[] triangle = [new(cx - 10, cy - 15), new(cx - 10, cy + 15), new(cx + 15, cy)]; + canvas.DrawVertices(SKVertexMode.Triangles, triangle, null, null, paint); + } + + using var image = surface.Snapshot(); + using var bitmap = SKBitmap.FromImage(image); + WriteJpeg(path, bitmap.Copy()); + return path; + } + + private static SKBitmap Render(SKBitmap source, int longSide) + { + var scale = Math.Min(1.0, (double)longSide / Math.Max(source.Width, source.Height)); + var width = Math.Max(1, (int)Math.Round(source.Width * scale)); + var height = Math.Max(1, (int)Math.Round(source.Height * scale)); + var result = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul)); + using var canvas = new SKCanvas(result); + canvas.Clear(SKColors.White); // JPEG has no alpha: transparent areas become white + using var image = SKImage.FromBitmap(source); + canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null); + return result; + } + + private static void WriteJpeg(string target, SKBitmap bitmap) + { + using (bitmap) + { + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp"; + try + { + using (var pixmap = bitmap.PeekPixels() ?? throw new InvalidOperationException("Miniatura senza pixel.")) + using (var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality)) + ?? throw new InvalidOperationException("Codifica JPEG della miniatura non riuscita.")) + using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write)) + { + data.SaveTo(file); + } + + try + { + File.Move(temp, target, overwrite: false); + } + catch (IOException) when (File.Exists(target)) + { + // Created meanwhile by another task: same content. + } + } + finally + { + if (File.Exists(temp)) + { + File.Delete(temp); + } + } + } + } + + private static void ValidateKey(string key) + { + ArgumentException.ThrowIfNullOrWhiteSpace(key); + if (key.Length < 8 || !key.All(Uri.IsHexDigit)) + { + throw new ArgumentException("La chiave di una miniatura è uno SHA-256 in esadecimale.", nameof(key)); + } + } +} diff --git a/src/Febe.Core/Library/VideoFrameExtractor.cs b/src/Febe.Core/Library/VideoFrameExtractor.cs new file mode 100644 index 0000000..8f78ee6 --- /dev/null +++ b/src/Febe.Core/Library/VideoFrameExtractor.cs @@ -0,0 +1,120 @@ +using System.Diagnostics; + +namespace Febe.Core.Library; + +/// +/// Extracts a frame from a video with ffmpeg, when ffmpeg is installed (spec §8.4: thumbnails of imported videos and of +/// videos without a cover). In Docker ffmpeg is part of the image (§11); on Windows it is optional. +/// +public sealed class VideoFrameExtractor +{ + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + + private VideoFrameExtractor(string executable) => Executable = executable; + + /// Full path of ffmpeg. + public string Executable { get; } + + /// Finds ffmpeg on the PATH (or at ); null when it is not available. + public static VideoFrameExtractor? TryCreate(string? explicitPath = null) + { + if (!string.IsNullOrWhiteSpace(explicitPath)) + { + return File.Exists(explicitPath) ? new VideoFrameExtractor(Path.GetFullPath(explicitPath)) : null; + } + + var name = OperatingSystem.IsWindows() ? "ffmpeg.exe" : "ffmpeg"; + var path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty; + foreach (var folder in path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + try + { + var candidate = Path.Combine(folder.Trim('"'), name); + if (File.Exists(candidate)) + { + return new VideoFrameExtractor(candidate); + } + } + catch (ArgumentException) + { + // A malformed PATH entry: skip it. + } + } + + return null; + } + + /// + /// A JPEG frame of the video, taken one second in (or the first frame of shorter videos); null when ffmpeg cannot + /// read the file. + /// + public async Task ExtractJpegAsync(string videoPath, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(videoPath); + foreach (var seek in new[] { "1", "0" }) + { + var frame = await RunAsync(videoPath, seek, ct).ConfigureAwait(false); + if (frame is { Length: > 0 }) + { + return frame; + } + } + + return null; + } + + private async Task RunAsync(string videoPath, string seek, CancellationToken ct) + { + var start = new ProcessStartInfo(Executable) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + RedirectStandardInput = false, + UseShellExecute = false, + CreateNoWindow = true, + }; + foreach (var argument in new[] { "-hide_banner", "-nostdin", "-v", "error", "-ss", seek, "-i", videoPath, "-frames:v", "1", "-f", "image2pipe", "-c:v", "mjpeg", "-q:v", "3", "-" }) + { + 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); + using var output = new MemoryStream(); + try + { + var copy = process.StandardOutput.BaseStream.CopyToAsync(output, timeout.Token); + var drainErrors = process.StandardError.ReadToEndAsync(timeout.Token); // never logged: may contain paths + await Task.WhenAll(copy, drainErrors).ConfigureAwait(false); + await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + try + { + process.Kill(entireProcessTree: true); + } + catch (InvalidOperationException) + { + } + + ct.ThrowIfCancellationRequested(); + return null; + } + + return process.ExitCode == 0 && output.Length > 0 ? output.ToArray() : null; + } +} diff --git a/src/Febe.Core/Library/WindowsFileNames.cs b/src/Febe.Core/Library/WindowsFileNames.cs new file mode 100644 index 0000000..24ea67b --- /dev/null +++ b/src/Febe.Core/Library/WindowsFileNames.cs @@ -0,0 +1,185 @@ +using System.Security.Cryptography; +using System.Text; + +namespace Febe.Core.Library; + +/// +/// Windows naming rules, applied on every platform (spec §4.7): the library may be read from Windows over a share, +/// and the same names must work everywhere. +/// +/// forbidden characters < > : " / \ | ? * and control characters become _; +/// reserved device names (CON, PRN, AUX, NUL, COM0–9, LPT0–9, COM¹²³, LPT¹²³, CONIN$, CONOUT$), also with an +/// extension, get a _ after the base name; +/// trailing dots and spaces are removed (so . and .. can never appear); +/// a segment is at most 255 characters; a whole path at most . +/// +/// +public static class WindowsFileNames +{ + /// Total path length kept below the classic Windows limit of 260 (spec §4.7: «percorsi oltre 240 caratteri»). + public const int MaxPathLength = 240; + + /// Maximum length of one path segment on NTFS. + public const int MaxSegmentLength = 255; + + /// Replacement for forbidden characters. + public const char Replacement = '_'; + + /// Length of the hash suffix added to shortened names (~ plus 8 hex digits). + private const int HashSuffixLength = 9; + + /// Shortest stem kept when shortening a name, before giving up. + private const int MinimumStem = 8; + + private static readonly HashSet ReservedNames = new(StringComparer.OrdinalIgnoreCase) + { + "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", + "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM¹", "COM²", "COM³", + "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "LPT¹", "LPT²", "LPT³", + }; + + /// True for a character Windows does not accept in a file name. + public static bool IsForbidden(char ch) => ch < 0x20 || ch is '<' or '>' or ':' or '"' or '/' or '\\' or '|' or '?' or '*'; + + /// True when the segment names a reserved device (with or without extension). + public static bool IsReservedName(string segment) + { + ArgumentNullException.ThrowIfNull(segment); + var dot = segment.IndexOf('.', StringComparison.Ordinal); + var stem = (dot < 0 ? segment : segment[..dot]).TrimEnd(' '); + return ReservedNames.Contains(stem); + } + + /// + /// Makes one path segment (a folder or file name) valid on Windows. Idempotent. Never returns an empty string, + /// . or ... + /// + public static string SanitizeSegment(string? segment) + { + var text = (segment ?? string.Empty).Normalize(NormalizationForm.FormC); + var builder = new StringBuilder(text.Length); + foreach (var ch in text) + { + builder.Append(IsForbidden(ch) ? Replacement : ch); + } + + var result = TrimTrailing(builder.ToString()); + if (result.Length == 0) + { + return Replacement.ToString(); + } + + if (IsReservedName(result)) + { + var dot = result.IndexOf('.', StringComparison.Ordinal); + result = dot < 0 ? result + Replacement : string.Concat(result.AsSpan(0, dot), Replacement.ToString(), result.AsSpan(dot)); + } + + if (result.Length > MaxSegmentLength) + { + result = Shorten(result, MaxSegmentLength, keepExtension: true); + } + + return result; + } + + /// + /// Fits a relative path (already sanitized segments, the last one a file name) under + /// so that the full path is at most characters. The file name is shortened first, + /// keeping its extension; then the longest folder segments. A shortened part ends with ~ and eight hex digits + /// of the SHA-256 of the original, so different names stay different (for example _1 and _2). + /// + /// Even shortened, the path does not fit (the base folder is too long). + public static IReadOnlyList FitPath(string baseFolder, IReadOnlyList segments, int maxLength = MaxPathLength) + { + ArgumentNullException.ThrowIfNull(baseFolder); + ArgumentNullException.ThrowIfNull(segments); + if (segments.Count == 0) + { + throw new ArgumentException("Il percorso è vuoto.", nameof(segments)); + } + + var parts = segments.ToArray(); + var baseLength = Path.TrimEndingDirectorySeparator(baseFolder).Length; + int Total() => baseLength + parts.Sum(p => p.Length + 1); + + var excess = Total() - maxLength; + if (excess <= 0) + { + return parts; + } + + // 1. The file name, keeping its extension. + var last = parts.Length - 1; + var (stem, extension) = SplitExtension(parts[last]); + var stemTarget = Math.Max(stem.Length - excess, Math.Min(stem.Length, MinimumStem + HashSuffixLength)); + if (stemTarget < stem.Length) + { + parts[last] = Shorten(parts[last], stemTarget + extension.Length, keepExtension: true); + excess = Total() - maxLength; + } + + // 2. Folder segments, longest first. + while (excess > 0) + { + var index = -1; + for (var i = 0; i < last; i++) + { + if (parts[i].Length > MinimumStem + HashSuffixLength && (index < 0 || parts[i].Length > parts[index].Length)) + { + index = i; + } + } + + if (index < 0) + { + throw new PathTooLongException( + $"Il percorso supera i {maxLength} caratteri anche accorciando i nomi: la cartella «{baseFolder}» è troppo lunga. " + + "Scegli una cartella con un percorso più corto."); + } + + var target = Math.Max(parts[index].Length - excess, MinimumStem + HashSuffixLength); + parts[index] = Shorten(parts[index], target, keepExtension: false); + excess = Total() - maxLength; + } + + return parts; + } + + /// Splits «name.ext» into («name», «.ext»). Names starting with a dot have no extension. + public static (string Stem, string Extension) SplitExtension(string fileName) + { + ArgumentNullException.ThrowIfNull(fileName); + var dot = fileName.LastIndexOf('.'); + return dot <= 0 || dot == fileName.Length - 1 || fileName.Length - dot > 16 + ? (fileName, string.Empty) + : (fileName[..dot], fileName[dot..]); + } + + /// Shortens a name to at most characters with a hash suffix of the original. + private static string Shorten(string name, int maxLength, bool keepExtension) + { + var (stem, extension) = keepExtension ? SplitExtension(name) : (name, string.Empty); + var room = maxLength - extension.Length - HashSuffixLength; + if (room < 1) + { + room = 1; + } + + if (stem.Length + extension.Length <= maxLength) + { + return name; + } + + var hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(name)))[..8]; + var cut = stem[..Math.Min(room, stem.Length)]; + if (cut.Length > 0 && char.IsHighSurrogate(cut[^1])) + { + cut = cut[..^1]; // never split a surrogate pair + } + + return TrimTrailing(cut) + "~" + hash + extension; + } + + private static string TrimTrailing(string value) => value.TrimEnd('.', ' '); +} diff --git a/src/Febe.Core/Storage/IAccountStore.cs b/src/Febe.Core/Storage/IAccountStore.cs new file mode 100644 index 0000000..db210a1 --- /dev/null +++ b/src/Febe.Core/Storage/IAccountStore.cs @@ -0,0 +1,99 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Storage; + +/// Accounts (spec §4.2, §8.3 account). +public interface IAccountStore +{ + Task GetAsync(long accountId, CancellationToken ct = default); + + /// The account with this Instagram identifier: the identity of an account. + Task FindByInstagramIdAsync(string instagramId, CancellationToken ct = default); + + /// Case-insensitive lookup by current user name. + Task FindByUsernameAsync(string username, CancellationToken ct = default); + + /// Alberto's own profile («Tu»), when known. + Task GetMineAsync(CancellationToken ct = default); + + /// All accounts, ordered by user name. + Task> ListAsync(CancellationToken ct = default); + + /// All accounts with their counts; «new» counts are entries discovered at or after . + Task> ListSummariesAsync(DateTimeOffset newSince, CancellationToken ct = default); + + Task GetStatsAsync(long accountId, CancellationToken ct = default); + + /// Adds an account and returns it with its key. + /// Another account has the same Instagram identifier, or is already «Tu». + Task AddAsync(Account account, CancellationToken ct = default); + + /// Replaces every field of an existing account (settings screen). + Task UpdateAsync(Account account, CancellationToken ct = default); + + Task SetStateAsync(long accountId, AccountState state, DateTimeOffset at, UnreachableReason? reason = null, CancellationToken ct = default); + + /// Updates last and next check times. Null values leave the stored value unchanged. + Task UpdateChecksAsync(long accountId, AccountCheckTimes times, CancellationToken ct = default); + + /// Stores the backfill resume point; marks the backfill as finished. + Task SetBackfillAsync(long accountId, string? cursor, DateTimeOffset? completedAt, CancellationToken ct = default); + + /// + /// Records a rename seen in the data (spec §4.2): updates the user name, keeps the folder (a default folder is + /// pinned to the old name) and raises the «Renamed» notice. + /// + Task RenameAsync(long accountId, string newUsername, DateTimeOffset at, CancellationToken ct = default); + + /// Adds notices (e.g. unrecognized format) to an account. + Task AddNoticesAsync(long accountId, AccountNotices notices, DateTimeOffset at, CancellationToken ct = default); + + /// Clears notices once Alberto has seen them. + Task ClearNoticesAsync(long accountId, AccountNotices notices, CancellationToken ct = default); + + /// + /// Removes the account record and, by cascade, its entries, files records and highlights. Files on disk are not + /// touched: removing an account with its files is a library operation, and the default is to keep them and make + /// the account «Solo archivio» (spec §4.2). + /// + Task DeleteAsync(long accountId, CancellationToken ct = default); +} + +/// Check times of an account; null values are left unchanged. +public sealed record AccountCheckTimes +{ + public DateTimeOffset? LastProfileCheckAt { get; init; } + + public DateTimeOffset? NextProfileCheckAt { get; init; } + + public DateTimeOffset? LastStoriesCheckAt { get; init; } + + public DateTimeOffset? NextStoriesCheckAt { get; init; } + + /// Profile facts read with the check (null: unchanged). + public int? PostCount { get; init; } + + public bool? IsPrivate { get; init; } + + public bool? IsFollowed { get; init; } + + public string? DisplayName { get; init; } +} + +/// A unique constraint refused a record (duplicate Instagram identifier, second «Tu», ...). +public sealed class DuplicateRecordException : Exception +{ + public DuplicateRecordException() + { + } + + public DuplicateRecordException(string message) + : base(message) + { + } + + public DuplicateRecordException(string message, Exception innerException) + : base(message, innerException) + { + } +} diff --git a/src/Febe.Core/Storage/IDuplicateStore.cs b/src/Febe.Core/Storage/IDuplicateStore.cs new file mode 100644 index 0000000..4b64269 --- /dev/null +++ b/src/Febe.Core/Storage/IDuplicateStore.cs @@ -0,0 +1,22 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Storage; + +/// Probable duplicates waiting for Alberto (spec §8.3 duplicate_pair, §9.3, §9.5). +public interface IDuplicateStore +{ + /// + /// Adds a pair. Idempotent: if the same pending pair (same sides) exists, it is returned unchanged. + /// + Task AddAsync(DuplicatePair pair, CancellationToken ct = default); + + Task GetAsync(long pairId, CancellationToken ct = default); + + /// Pending pairs in creation order, after . + Task> ListPendingAsync(DuplicateOrigin? origin = null, long afterId = 0, int limit = 200, CancellationToken ct = default); + + Task CountPendingAsync(DuplicateOrigin? origin = null, CancellationToken ct = default); + + /// Records Alberto's decision. Applying it to files is the caller's job. + Task DecideAsync(long pairId, DuplicateDecision decision, DateTimeOffset at, CancellationToken ct = default); +} diff --git a/src/Febe.Core/Storage/IEngineStores.cs b/src/Febe.Core/Storage/IEngineStores.cs new file mode 100644 index 0000000..24399df --- /dev/null +++ b/src/Febe.Core/Storage/IEngineStores.cs @@ -0,0 +1,163 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; + +namespace Febe.Core.Storage; + +/// The engine queue (spec §8.3 task). Persisted: a restart resets nothing. +public interface ITaskStore +{ + /// + /// Enqueues a task. If a pending task with the same kind, account and payload exists, it is kept and moved earlier + /// (earliest due time, highest priority, manual flag kept) instead of adding a second one; that task is returned. + /// + Task EnqueueAsync(EngineTask task, CancellationToken ct = default); + + Task GetAsync(long taskId, CancellationToken ct = default); + + /// Pending tasks due at : highest priority first, then earliest due, then oldest. + Task> PeekDueAsync(DateTimeOffset now, int limit, CancellationToken ct = default); + + /// Pending tasks by due time (the queue shown in Attività, «verso le»). + Task> ListPendingAsync(int limit, CancellationToken ct = default); + + /// Pending → Running, atomically. False if the task was not pending any more. + Task TryStartAsync(long taskId, DateTimeOffset at, CancellationToken ct = default); + + /// Running → Done. + Task CompleteAsync(long taskId, DateTimeOffset at, CancellationToken ct = default); + + /// + /// Records a failure: with the task goes back to pending at that time, otherwise it + /// becomes Failed. Attempts are incremented. + /// + Task FailAsync(long taskId, DateTimeOffset at, string error, DateTimeOffset? retryAt, CancellationToken ct = default); + + Task RescheduleAsync(long taskId, DateTimeOffset dueAt, CancellationToken ct = default); + + Task CancelAsync(long taskId, DateTimeOffset at, CancellationToken ct = default); + + /// Cancels every pending task of an account. Returns how many. + Task CancelForAccountAsync(long accountId, DateTimeOffset at, CancellationToken ct = default); + + /// At start-up: tasks left running by a previous process go back to pending. Returns how many. + Task RequeueRunningAsync(CancellationToken ct = default); + + /// Deletes finished tasks (done, failed, cancelled) completed before . + Task PurgeFinishedAsync(DateTimeOffset before, CancellationToken ct = default); +} + +/// Counted actions toward the site (spec §7.4 action_log): the budgets are computed from here, not in memory. +public interface IActionLogStore +{ + Task AppendAsync(ActionLogRecord record, CancellationToken ct = default); + + /// Sum of amounts of a category in [from, to), optionally for one account. + Task SumAsync(ActionKind category, DateTimeOffset from, DateTimeOffset to, long? accountId = null, CancellationToken ct = default); + + /// + /// Usage of every category: the rolling window (now − 60 min, now] and the local calendar day of + /// in . Categories without actions are included with zero. + /// + Task> GetUsageAsync(DateTimeOffset now, TimeZoneInfo zone, CancellationToken ct = default); + + /// Time of the last action (of a category, or of any category except data downloads when null). + Task GetLastActionAtAsync(ActionKind? category = null, CancellationToken ct = default); + + /// Actions in [from, to), oldest first. + Task> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default); + + /// Deletes actions older than . Keep at least two days for the daily budgets. + Task PruneAsync(DateTimeOffset before, CancellationToken ct = default); +} + +/// Engine sessions (spec §8.3 session). +public interface ISessionStore +{ + Task StartAsync(DateTimeOffset at, CancellationToken ct = default); + + Task EndAsync(long sessionId, DateTimeOffset at, SessionOutcome outcome, int actionCount, string? summary = null, CancellationToken ct = default); + + Task GetAsync(long sessionId, CancellationToken ct = default); + + /// The most recently started session. + Task GetLastAsync(CancellationToken ct = default); + + /// Sessions overlapping [from, to), by start time (strip of the day). + Task> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default); + + /// At start-up: sessions left open become Interrupted, ended at . Returns how many. + Task CloseInterruptedAsync(DateTimeOffset at, CancellationToken ct = default); +} + +/// Stops of the circuit breaker (spec §7.6, §8.3 incident). +public interface IIncidentStore +{ + /// Opens an incident and returns it with its key. + Task OpenAsync(Incident incident, CancellationToken ct = default); + + Task ResolveAsync(long incidentId, DateTimeOffset at, CancellationToken ct = default); + + Task GetAsync(long incidentId, CancellationToken ct = default); + + /// Unresolved incidents, oldest first. + Task> ListOpenAsync(CancellationToken ct = default); + + /// Incidents that started in [from, to), oldest first. + Task> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default); + + /// Incidents of a level since an instant («tre rallentamenti in sette giorni»; «la seconda nelle 24 ore»). + Task CountAsync(SignalLevel level, DateTimeOffset since, CancellationToken ct = default); +} + +/// The readable timeline (spec §8.3 event). +public interface IEventStore +{ + Task AppendAsync(EventRecord record, CancellationToken ct = default); + + /// A page of the timeline, newest first. + Task> ListAsync(EventQuery query, CancellationToken ct = default); + + /// Events after a known one, oldest first: incremental updates of the interface. + Task> ListAfterAsync(long afterId, int limit = 200, CancellationToken ct = default); + + Task PruneAsync(DateTimeOffset before, CancellationToken ct = default); +} + +/// A page of the timeline: newest first, before when given. +public sealed record EventQuery +{ + public long? BeforeId { get; init; } + + public int Limit { get; init; } = 100; + + public long? AccountId { get; init; } + + public EventSeverity? MinSeverity { get; init; } + + public DateTimeOffset? From { get; init; } + + public DateTimeOffset? To { get; init; } +} + +/// Local copy of the list of profiles Alberto follows (spec §4.2, §8.3 following). +public interface IFollowingStore +{ + /// + /// Adds or updates profiles as they are read (page by page, possibly over several sessions). Matches by Instagram + /// identifier when present, otherwise by user name. + /// + Task UpsertAsync(IReadOnlyList records, CancellationToken ct = default); + + /// The list in reading order. + Task> ListAsync(CancellationToken ct = default); + + Task CountAsync(CancellationToken ct = default); + + /// When the most recent profile was read. + Task GetLastReadAtAsync(CancellationToken ct = default); + + /// After a complete re-read started at : removes profiles not seen (unfollowed). + Task RemoveNotReadSinceAsync(DateTimeOffset readStartedAt, CancellationToken ct = default); + + Task ClearAsync(CancellationToken ct = default); +} diff --git a/src/Febe.Core/Storage/IEntryStore.cs b/src/Febe.Core/Storage/IEntryStore.cs new file mode 100644 index 0000000..82900ff --- /dev/null +++ b/src/Febe.Core/Storage/IEntryStore.cs @@ -0,0 +1,76 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Storage; + +/// Entries (spec §4.3, §8.3 entry) and the library queries of the interface (spec §4.6). +public interface IEntryStore +{ + Task GetAsync(long entryId, CancellationToken ct = default); + + Task GetWithMediaAsync(long entryId, CancellationToken ct = default); + + /// The entry with this identity, in any state (deleted included). + Task FindAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default); + + /// + /// «Is this Instagram identifier known?» for (account, kind), in any state — deleted entries count as known so + /// they are never downloaded again (spec §4.6). + /// + Task IsKnownAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default); + + /// Which of these identifiers are already known for (account, kind), in any state. For readers: one query per page. + Task> GetKnownInstagramIdsAsync(long accountId, EntryKind kind, IReadOnlyCollection instagramIds, CancellationToken ct = default); + + /// Entries of an account with this Instagram identifier, any kind and state (e.g. a story that entered a highlight). + Task> FindByInstagramIdAsync(long accountId, string instagramId, CancellationToken ct = default); + + /// + /// An entry of (account, kind) published within of : + /// recognizes imported entries that have no Instagram identifier (spec §9.5, two seconds). + /// + Task FindByPublicationTimeAsync(long accountId, EntryKind kind, DateTimeOffset publishedAt, TimeSpan tolerance, CancellationToken ct = default); + + /// + /// Adds an entry with its files in one transaction. Idempotent on (account, kind, Instagram identifier): when the + /// entry is already known, nothing changes and the stored entry is returned with Created = false. + /// Positions of the files must be distinct. + /// + Task AddAsync(Entry entry, IReadOnlyList media, CancellationToken ct = default); + + /// Adds many entries in one transaction (import, rebuild). Same semantics as . + Task> AddManyAsync(IReadOnlyList entries, CancellationToken ct = default); + + /// Replaces the mutable fields of an entry (Instagram identifier, code, caption, author, state, dates). + Task UpdateAsync(Entry entry, CancellationToken ct = default); + + Task SetStateAsync(long entryId, EntryState state, CancellationToken ct = default); + + /// Recomputes the state of an entry from its files (). + Task RecomputeStateAsync(long entryId, CancellationToken ct = default); + + /// + /// «Eliminato»: the entry stays without files so it is not downloaded again (spec §4.6). Its files become + /// and lose their path and perceptual hash; SHA-256 and size are kept. Deleting files on disk is the caller's job. + /// + Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default); + + /// «Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade). + Task RemoveAsync(long entryId, CancellationToken ct = default); + + /// Entries of an account ordered by publication time, newest first (account tabs, collection pipeline). + Task> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default); + + /// Entries of (account, kind) discovered in [from, to): per-account daily backfill limit. + Task CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default); + + /// A window of the library mosaic with keyset paging: stays fast over 200,000 entries. + Task QueryLibraryAsync(LibraryQuery query, CancellationToken ct = default); + + Task GetLibraryTotalsAsync(LibraryFilter filter, CancellationToken ct = default); + + /// Entries per local calendar day in Alberto's zone, newest day first. + Task> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, CancellationToken ct = default); + + /// Tiles for given entries, in the given order (e.g. the items of a highlight collection). + Task> GetTilesAsync(IReadOnlyList entryIds, CancellationToken ct = default); +} diff --git a/src/Febe.Core/Storage/IFebeStorage.cs b/src/Febe.Core/Storage/IFebeStorage.cs new file mode 100644 index 0000000..b9a3619 --- /dev/null +++ b/src/Febe.Core/Storage/IFebeStorage.cs @@ -0,0 +1,58 @@ +namespace Febe.Core.Storage; + +/// +/// Everything Febe keeps in its database, as one object (implemented by Febe.Data.FebeDatabase). +/// Writes are serialized by a single writer; reads run concurrently. +/// +public interface IFebeStorage : IAsyncDisposable +{ + IAccountStore Accounts { get; } + + IEntryStore Entries { get; } + + IMediaStore Media { get; } + + IHighlightStore Highlights { get; } + + IDuplicateStore Duplicates { get; } + + ITaskStore Tasks { get; } + + IActionLogStore ActionLog { get; } + + ISessionStore Sessions { get; } + + IIncidentStore Incidents { get; } + + IEventStore Events { get; } + + IFollowingStore Following { get; } + + IImportStore Imports { get; } + + ISettingsStore Settings { get; } + + IDatabaseMaintenance Maintenance { get; } +} + +/// Maintenance of the database file. +public interface IDatabaseMaintenance +{ + /// Full path of the database file. + string DatabasePath { get; } + + /// Schema version (PRAGMA user_version). + int SchemaVersion { get; } + + /// + /// Writes a consistent copy of the database to a new file with VACUUM INTO (spec §8.5). + /// The destination must not exist. + /// + Task BackupToAsync(string destinationFile, CancellationToken ct = default); + + /// Runs PRAGMA quick_check; true when the database is sound. + Task CheckIntegrityAsync(CancellationToken ct = default); + + /// Lets SQLite refresh its statistics (PRAGMA optimize). + Task OptimizeAsync(CancellationToken ct = default); +} diff --git a/src/Febe.Core/Storage/IHighlightStore.cs b/src/Febe.Core/Storage/IHighlightStore.cs new file mode 100644 index 0000000..df5e04d --- /dev/null +++ b/src/Febe.Core/Storage/IHighlightStore.cs @@ -0,0 +1,41 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Storage; + +/// Highlight collections and their ordered contents (spec §8.3 highlight, highlight_entry). +public interface IHighlightStore +{ + Task GetAsync(long highlightId, CancellationToken ct = default); + + /// Collections of an account in profile order. + Task> ListAsync(long accountId, bool includeRemoved = false, CancellationToken ct = default); + + Task FindAsync(long accountId, string instagramId, CancellationToken ct = default); + + /// Lookup by title, for collections known only from an import or a rebuild. + Task FindByTitleAsync(long accountId, string title, CancellationToken ct = default); + + /// + /// Adds or updates a collection. Matches an existing one by key, then by (account, Instagram identifier). + /// Returns the stored collection. + /// + Task UpsertAsync(Highlight highlight, CancellationToken ct = default); + + /// Sets the profile order of the given collections (positions 0, 1, ...). + Task SetOrderAsync(long accountId, IReadOnlyList highlightIdsInOrder, CancellationToken ct = default); + + /// The collection disappeared from the profile; its contents and files stay. + Task MarkRemovedAsync(long highlightId, DateTimeOffset at, CancellationToken ct = default); + + /// Contents of a collection in order. + Task> ListItemsAsync(long highlightId, CancellationToken ct = default); + + /// Replaces the contents of a collection with these entries, in this order. + Task SetItemsAsync(long highlightId, IReadOnlyList entryIdsInOrder, CancellationToken ct = default); + + /// Appends an entry at the end of a collection if it is not there yet. + Task AddItemAsync(long highlightId, long entryId, CancellationToken ct = default); + + /// Collections that contain an entry (an entry may be in several). + Task> ListForEntryAsync(long entryId, CancellationToken ct = default); +} diff --git a/src/Febe.Core/Storage/IImportStore.cs b/src/Febe.Core/Storage/IImportStore.cs new file mode 100644 index 0000000..a5b8556 --- /dev/null +++ b/src/Febe.Core/Storage/IImportStore.cs @@ -0,0 +1,71 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Storage; + +/// Imports and their files (spec §8.3 import_run, import_file; §9). +public interface IImportStore +{ + Task CreateRunAsync(ImportRun run, CancellationToken ct = default); + + Task UpdateRunAsync(ImportRun run, CancellationToken ct = default); + + Task GetRunAsync(long runId, CancellationToken ct = default); + + /// Imports, newest first. + Task> ListRunsAsync(CancellationToken ct = default); + + /// + /// Adds files to an import in one transaction. Files already recorded for the same relative path are left + /// unchanged (so an interrupted analysis resumes). + /// + Task AddFilesAsync(IReadOnlyList files, CancellationToken ct = default); + + Task UpdateFileAsync(ImportFile file, CancellationToken ct = default); + + Task UpdateFilesAsync(IReadOnlyList files, CancellationToken ct = default); + + Task GetFileAsync(long fileId, CancellationToken ct = default); + + Task FindFileAsync(long runId, string relativePath, CancellationToken ct = default); + + /// Files of an import, by key, with optional filters. + Task> ListFilesAsync(ImportFileQuery query, CancellationToken ct = default); + + /// Files of the same import with this SHA-256 (duplicates inside the source). + Task> FindFilesBySha256Async(long runId, string sha256, CancellationToken ct = default); + + /// Counts by outcome and by state. + Task GetSummaryAsync(long runId, CancellationToken ct = default); + + /// Source folders with their counts and association (review, mockup 09). + Task> ListFoldersAsync(long runId, CancellationToken ct = default); + + /// Associates every file of a source folder with an account (null: not associated). + Task SetFolderTargetAsync(long runId, string folder, long? accountId, CancellationToken ct = default); +} + +/// Filters for the files of an import. +public sealed record ImportFileQuery +{ + public required long RunId { get; init; } + + public ImportOutcome? Outcome { get; init; } + + public ImportFileState? State { get; init; } + + public string? Folder { get; init; } + + public long AfterId { get; init; } + + public int Limit { get; init; } = 500; +} + +/// Counts of an import. +public sealed record ImportSummary( + int Total, + IReadOnlyDictionary ByOutcome, + IReadOnlyDictionary ByState, + long Bytes); + +/// A source folder of an import. +public sealed record ImportFolder(string Folder, int Files, string? ProbableAccount, long? TargetAccountId); diff --git a/src/Febe.Core/Storage/IMediaStore.cs b/src/Febe.Core/Storage/IMediaStore.cs new file mode 100644 index 0000000..9c706c1 --- /dev/null +++ b/src/Febe.Core/Storage/IMediaStore.cs @@ -0,0 +1,52 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Storage; + +/// Files of entries (spec §8.3 media), hashes and the download queue. +public interface IMediaStore +{ + Task GetAsync(long mediaId, CancellationToken ct = default); + + /// Files of an entry in position order. + Task> ListByEntryAsync(long entryId, CancellationToken ct = default); + + /// + /// Every file with this SHA-256 across the whole library, any state, with its entry and account + /// («Già in libreria», spec §9.3; exact duplicates after a download, §9.5). + /// + Task> FindBySha256Async(string sha256, CancellationToken ct = default); + + /// + /// Relative paths of the files of an account that have one, with their entry: recognizes entries without an + /// Instagram identifier (imported) by their files (rebuild, import resume). + /// + Task> MapPathsAsync(long accountId, CancellationToken ct = default); + + /// Perceptual hashes of the photos present in the library, to load the in-memory index. + Task> LoadPerceptualHashesAsync(CancellationToken ct = default); + + /// + /// Files waiting to be downloaded, in queue order: stories first (they expire), then by expiry and discovery. + /// + Task> ListPendingDownloadsAsync(int limit, CancellationToken ct = default); + + /// Files waiting to be downloaded, for one account or overall («lo storico non corre più veloce dei download»). + Task CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default); + + /// Records a file now on disk and recomputes the state of its entry, in one transaction. + Task MarkStoredAsync(long mediaId, StoredFile file, MediaState state, DateTimeOffset at, CancellationToken ct = default); + + /// + /// Records a failed attempt: is Failed, Expired (address expired) or Skipped (a limit). + /// Increments attempts and recomputes the state of the entry. + /// + Task MarkFailedAsync(long mediaId, MediaState state, string? error, DateTimeOffset at, CancellationToken ct = default); + + /// A fresh address read from the page: the file goes back to «da scaricare». + Task UpdateSourceAsync(long mediaId, string? sourceUrl, string? coverUrl, DateTimeOffset seenAt, CancellationToken ct = default); + + Task SetThumbnailAsync(long mediaId, bool hasThumbnail, CancellationToken ct = default); + + /// Replaces every field of a file record. + Task UpdateAsync(Media media, CancellationToken ct = default); +} diff --git a/src/Febe.Core/Storage/ISettingsStore.cs b/src/Febe.Core/Storage/ISettingsStore.cs new file mode 100644 index 0000000..2eeafb6 --- /dev/null +++ b/src/Febe.Core/Storage/ISettingsStore.cs @@ -0,0 +1,63 @@ +using System.Globalization; + +namespace Febe.Core.Storage; + +/// Key-value settings (spec §8.3 setting). Keys are listed in . +public interface ISettingsStore +{ + Task GetAsync(string key, CancellationToken ct = default); + + /// Stores a value; null removes the key. + Task SetAsync(string key, string? value, CancellationToken ct = default); + + /// Stores several values in one transaction; null values remove their key. + Task SetManyAsync(IReadOnlyDictionary values, CancellationToken ct = default); + + Task> GetAllAsync(CancellationToken ct = default); +} + +/// Known setting keys. Values are invariant-culture text. +public static class SettingKeys +{ + /// Library folder (spec §4.7 «Libreria»). + public const string LibraryRoot = "libreria.cartella"; + + /// General naming scheme. + public const string NamingScheme = "libreria.schema"; + + /// Naming scheme for highlight collections. + public const string HighlightNamingScheme = "libreria.schema-evidenza"; + + /// «Imposta la data del file a quella di pubblicazione» (true/false). + public const string SetFileTimeToPublication = "libreria.data-file-pubblicazione"; +} + +/// Typed helpers over . +public static class SettingsStoreExtensions +{ + public static async Task GetBoolAsync(this ISettingsStore store, string key, bool fallback, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(store); + var text = await store.GetAsync(key, ct).ConfigureAwait(false); + return bool.TryParse(text, out var value) ? value : fallback; + } + + public static Task SetBoolAsync(this ISettingsStore store, string key, bool value, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(store); + return store.SetAsync(key, value ? "true" : "false", ct); + } + + public static async Task GetInt64Async(this ISettingsStore store, string key, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(store); + var text = await store.GetAsync(key, ct).ConfigureAwait(false); + return long.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : null; + } + + public static Task SetInt64Async(this ISettingsStore store, string key, long? value, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(store); + return store.SetAsync(key, value?.ToString(CultureInfo.InvariantCulture), ct); + } +} diff --git a/src/Febe.Core/Storage/LibraryQueries.cs b/src/Febe.Core/Storage/LibraryQueries.cs new file mode 100644 index 0000000..c36bb49 --- /dev/null +++ b/src/Febe.Core/Storage/LibraryQueries.cs @@ -0,0 +1,181 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Storage; + +/// Kind filter of the library (mockup 01): «Foto» and «Video» concern posts; the others have their own entry. +public enum LibraryKindFilter +{ + /// «Tutto»: posts, stories, highlights and tagged posts. Profile pictures are not in the library (spec §4.3). + All, + + /// «Foto»: posts with at least one photo. + Photos, + + /// «Video»: posts with at least one video (reels included). + Videos, + + /// «Storie». + Stories, + + /// «In evidenza»: highlight items, including stories referenced by a collection. + Highlights, + + /// «Taggati». + Tagged, + + /// Profile pictures: the «Profilo» tab of an account. + ProfilePictures, + + /// Posts of any media (the «Post» tab of an account). + Posts, +} + +/// Filters of the library mosaic and of the account tabs (spec §4.6). +public sealed record LibraryFilter +{ + public LibraryKindFilter Kind { get; init; } = LibraryKindFilter.All; + + /// Only these accounts (null: all). + public IReadOnlyList? AccountIds { get; init; } + + /// Published at or after (UTC). + public DateTimeOffset? From { get; init; } + + /// Published before (UTC). + public DateTimeOffset? To { get; init; } + + /// «Provenienza»: downloaded or imported (null: both). + public Provenance? Provenance { get; init; } + + /// + /// Search by account name (user name or display name) and caption text. Case and accents are ignored. + /// + public string? Search { get; init; } + + /// Entry states shown. Null means (entries with files). + public IReadOnlyList? States { get; init; } +} + +/// Keyset position in the library order (publication time descending, then id descending). +public readonly record struct LibraryCursor(DateTimeOffset PublishedAt, long EntryId) +{ + /// A cursor that starts the older direction at a given instant (to jump to a date). + public static LibraryCursor At(DateTimeOffset instant) => new(instant, long.MaxValue); +} + +public enum LibraryDirection +{ + /// Entries published before the cursor (scrolling down). + Older, + + /// Entries published after the cursor (scrolling up, or new entries arriving on top). + Newer, +} + +/// A window of the library. Without a cursor the window starts from the newest entry. +public sealed record LibraryQuery +{ + public LibraryFilter Filter { get; init; } = new(); + + public LibraryCursor? Cursor { get; init; } + + public LibraryDirection Direction { get; init; } = LibraryDirection.Older; + + /// Maximum tiles (1–1000). + public int Limit { get; init; } = 200; +} + +/// +/// One tile of the mosaic: an entry with its cover file (the file at the lowest position). +/// is the thumbnail key. +/// +public sealed record LibraryTile( + long EntryId, + long AccountId, + string Username, + EntryKind Kind, + DateTimeOffset PublishedAt, + EntryState State, + Provenance Provenance, + int MediaCount, + long? CoverMediaId, + MediaKind? CoverKind, + int? CoverWidth, + int? CoverHeight, + TimeSpan? CoverDuration, + string? CoverSha256, + bool CoverHasThumbnail); + +/// +/// A window of tiles, always in display order (newest first). and continue +/// the window in each direction; null means there is nothing more that way. +/// +public sealed record LibraryPage(IReadOnlyList Tiles, LibraryCursor? Older, LibraryCursor? Newer); + +/// Number of entries of a local calendar day (headers of the mosaic, «14 nuovi elementi»). +public readonly record struct DayCount(DateOnly Day, int Count); + +/// Totals for the title of the library («48.212 elementi di 38 account»). +public readonly record struct LibraryTotals(int Entries, int Accounts); + +/// Options of a per-account list of entries. +public sealed record EntryListOptions +{ + /// Only this kind (null: all). + public EntryKind? Kind { get; init; } + + /// Only these states (null: all, deleted included). + public IReadOnlyList? States { get; init; } + + /// Continue after this cursor (publication time descending). + public LibraryCursor? Before { get; init; } + + public int Limit { get; init; } = 200; +} + +/// Counts of an account (header of the account card, mockup 05; list of mockup 03). +public sealed record AccountStats +{ + public long AccountId { get; init; } + + /// Entries in the library (with files), all kinds except profile pictures. + public int EntriesInLibrary { get; init; } + + public int Posts { get; init; } + + public int Stories { get; init; } + + public int HighlightItems { get; init; } + + public int Tagged { get; init; } + + public int ProfilePictures { get; init; } + + /// Highlight collections on the profile (not removed). + public int HighlightCollections { get; init; } + + /// Bytes of the files present. + public long Bytes { get; init; } + + /// Files still to download. + public int PendingFiles { get; init; } + + public DateTimeOffset? LastPublishedAt { get; init; } +} + +/// An account with its counts, for the accounts list. +/// The account. +/// «In libreria». +/// Posts in the library (backfill progress: «340 di 1.280 post»). +/// Posts discovered since the given instant («1 nuovo post oggi»). +/// Stories discovered since the given instant («2 nuove storie oggi»). +public sealed record AccountSummary(Account Account, int EntriesInLibrary, int Posts, int NewPostsSince, int NewStoriesSince); + +/// A perceptual hash of a library file, to load the in-memory index. +public readonly record struct PerceptualHashRecord(long MediaId, long AccountId, ulong Hash); + +/// Result of adding an entry: the stored entry and whether it was new. +public sealed record AddEntryResult(EntryWithMedia Stored, bool Created); + +/// An entry to add with its files. +public sealed record NewEntry(Entry Entry, IReadOnlyList Media); diff --git a/src/Febe.Data/FebeDatabase.cs b/src/Febe.Data/FebeDatabase.cs new file mode 100644 index 0000000..e3ebcf8 --- /dev/null +++ b/src/Febe.Data/FebeDatabase.cs @@ -0,0 +1,230 @@ +using Febe.Core.Storage; +using Febe.Data.Stores; +using Microsoft.Data.Sqlite; + +namespace Febe.Data; + +/// +/// The SQLite database of Febe (spec §8): Dati/febe.sqlite in WAL mode, foreign keys on, busy timeout, +/// numbered migrations applied at start-up. All writes go through one queue and one connection +/// (); reads use separate pooled read-only connections and never block the writer. +/// +public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance +{ + /// File name inside the Data folder. + public const string FileName = "febe.sqlite"; + + private const int BusyTimeoutMs = 10_000; + + private readonly SqliteConnection _writerConnection; + private readonly string _readConnectionString; + private int _disposed; + + private FebeDatabase(string path, SqliteConnection writerConnection, string readConnectionString, int schemaVersion) + { + DatabasePath = path; + _writerConnection = writerConnection; + _readConnectionString = readConnectionString; + SchemaVersion = schemaVersion; + Writer = new SqliteWriter(writerConnection); + + Accounts = new AccountStore(this); + Entries = new EntryStore(this); + Media = new MediaStore(this); + Highlights = new HighlightStore(this); + Duplicates = new DuplicateStore(this); + Tasks = new TaskStore(this); + ActionLog = new ActionLogStore(this); + Sessions = new SessionStore(this); + Incidents = new IncidentStore(this); + Events = new EventStore(this); + Following = new FollowingStore(this); + Imports = new ImportStore(this); + Settings = new SettingsStore(this); + } + + public IAccountStore Accounts { get; } + + public IEntryStore Entries { get; } + + public IMediaStore Media { get; } + + public IHighlightStore Highlights { get; } + + public IDuplicateStore Duplicates { get; } + + public ITaskStore Tasks { get; } + + public IActionLogStore ActionLog { get; } + + public ISessionStore Sessions { get; } + + public IIncidentStore Incidents { get; } + + public IEventStore Events { get; } + + public IFollowingStore Following { get; } + + public IImportStore Imports { get; } + + public ISettingsStore Settings { get; } + + public IDatabaseMaintenance Maintenance => this; + + public string DatabasePath { get; } + + public int SchemaVersion { get; } + + internal SqliteWriter Writer { get; } + + /// Opens (or creates) febe.sqlite inside the Data folder and applies pending migrations. + public static Task OpenAsync(string dataFolder, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder); + return OpenFileAsync(Path.Combine(dataFolder, FileName), ct); + } + + /// Opens (or creates) a database file and applies pending migrations. + public static Task OpenFileAsync(string databasePath, CancellationToken ct = default) => + Task.FromResult(Open(databasePath, MigrationRunner.LoadEmbedded(), ct)); + + internal static FebeDatabase Open(string databasePath, IReadOnlyList migrations, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(databasePath); + ct.ThrowIfCancellationRequested(); + var path = Path.GetFullPath(databasePath); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + + var writerConnectionString = new SqliteConnectionStringBuilder + { + DataSource = path, + Mode = SqliteOpenMode.ReadWriteCreate, + Cache = SqliteCacheMode.Private, + Pooling = false, + ForeignKeys = true, + DefaultTimeout = BusyTimeoutMs / 1000, + }.ToString(); + + var readConnectionString = new SqliteConnectionStringBuilder + { + DataSource = path, + Mode = SqliteOpenMode.ReadOnly, + Cache = SqliteCacheMode.Private, + Pooling = true, + DefaultTimeout = BusyTimeoutMs / 1000, + }.ToString(); + + var connection = new SqliteConnection(writerConnectionString); + try + { + connection.Open(); + var mode = connection.Command("PRAGMA journal_mode = WAL").ExecuteScalar() as string; + if (!string.Equals(mode, "wal", StringComparison.OrdinalIgnoreCase)) + { + throw new DatabaseMigrationException( + $"Febe non riesce a mettere il database in modalità WAL (modalità attuale: {mode}). La cartella dei dati deve stare su un disco locale."); + } + + connection.Command("PRAGMA synchronous = NORMAL").ExecuteNonQuery(); + connection.Command($"PRAGMA busy_timeout = {BusyTimeoutMs}").ExecuteNonQuery(); + connection.Command("PRAGMA foreign_keys = ON").ExecuteNonQuery(); + var version = MigrationRunner.Apply(connection, migrations); + return new FebeDatabase(path, connection, readConnectionString, version); + } + catch + { + connection.Dispose(); + throw; + } + } + + /// Queues a write; the task completes after the commit. + internal Task WriteAsync(Func work, CancellationToken ct) => Writer.ExecuteAsync(work, ct); + + internal Task WriteAsync(Action work, CancellationToken ct) => Writer.ExecuteAsync(work, ct); + + /// Runs a read on its own read-only connection. + internal Task ReadAsync(Func work, CancellationToken ct) + { + if (ct.IsCancellationRequested) + { + return Task.FromCanceled(ct); + } + + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + try + { + using var connection = OpenReadConnection(); + return Task.FromResult(work(connection)); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + return Task.FromException(ex); + } + } + + internal SqliteConnection OpenReadConnection() + { + var connection = new SqliteConnection(_readConnectionString); + connection.Open(); + return connection; + } + + public Task BackupToAsync(string destinationFile, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(destinationFile); + var destination = Path.GetFullPath(destinationFile); + if (File.Exists(destination)) + { + throw new IOException($"La copia {destination} esiste già: Febe non la sovrascrive."); + } + + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + return ReadAsync( + connection => + { + // VACUUM INTO reads a consistent snapshot; it works on a read-only connection and does not block the writer. + connection.Command("VACUUM INTO @destination").With("@destination", destination).ExecuteNonQuery(); + return true; + }, + ct); + } + + public Task CheckIntegrityAsync(CancellationToken ct = default) => + ReadAsync( + connection => + { + using var reader = connection.Command("PRAGMA quick_check").ExecuteReader(); + return reader.Read() && string.Equals(reader.GetString(0), "ok", StringComparison.OrdinalIgnoreCase) && !reader.Read(); + }, + ct); + + public Task OptimizeAsync(CancellationToken ct = default) => + WriteAsync(context => context.Command("PRAGMA optimize").ExecuteNonQuery(), ct); + + public ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return ValueTask.CompletedTask; + } + + Writer.Dispose(); + try + { + _writerConnection.Command("PRAGMA wal_checkpoint(TRUNCATE)").ExecuteNonQuery(); + } + catch (SqliteException) + { + // A reader may still hold a snapshot: the checkpoint is an optimization, not a requirement. + } + + _writerConnection.Dispose(); + using (var pooled = new SqliteConnection(_readConnectionString)) + { + SqliteConnection.ClearPool(pooled); + } + + return ValueTask.CompletedTask; + } +} diff --git a/src/Febe.Data/MigrationRunner.cs b/src/Febe.Data/MigrationRunner.cs new file mode 100644 index 0000000..6eda13c --- /dev/null +++ b/src/Febe.Data/MigrationRunner.cs @@ -0,0 +1,138 @@ +using System.Globalization; +using System.Reflection; +using System.Text.RegularExpressions; +using Microsoft.Data.Sqlite; + +namespace Febe.Data; + +/// A numbered SQL migration (src/Febe.Data/Migrations/NNNN_name.sql). +internal sealed record Migration(int Version, string Name, string Sql); + +/// The database was written by a newer Febe, or a migration failed. +public sealed class DatabaseMigrationException : Exception +{ + public DatabaseMigrationException() + { + } + + public DatabaseMigrationException(string message) + : base(message) + { + } + + public DatabaseMigrationException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// +/// Applies the numbered migrations at start-up (spec §8.3): each one inside its own transaction, with the schema +/// version in PRAGMA user_version, so a failed migration leaves the database at the previous version. +/// +internal static partial class MigrationRunner +{ + [GeneratedRegex(@"(?:^|[._])(?\d{4})_(?[A-Za-z0-9_\-]+)\.sql$", RegexOptions.CultureInvariant)] + private static partial Regex MigrationName(); + + /// The migrations embedded in this assembly, in version order. + public static IReadOnlyList LoadEmbedded() + { + var assembly = typeof(MigrationRunner).Assembly; + var migrations = new List(); + foreach (var resource in assembly.GetManifestResourceNames()) + { + var match = MigrationName().Match(resource); + if (!match.Success) + { + continue; + } + + using var stream = assembly.GetManifestResourceStream(resource) + ?? throw new DatabaseMigrationException($"Migrazione {resource} non leggibile."); + using var reader = new StreamReader(stream); + migrations.Add(new Migration( + int.Parse(match.Groups["version"].Value, CultureInfo.InvariantCulture), + match.Groups["name"].Value, + reader.ReadToEnd())); + } + + return Validate(migrations); + } + + /// Checks that versions are 1, 2, 3, ... without gaps or duplicates and returns them ordered. + public static IReadOnlyList Validate(IEnumerable migrations) + { + var ordered = migrations.OrderBy(m => m.Version).ToList(); + for (var i = 0; i < ordered.Count; i++) + { + if (ordered[i].Version != i + 1) + { + throw new DatabaseMigrationException( + $"Le migrazioni devono essere numerate 1, 2, 3, ... senza buchi né doppioni: trovata la {ordered[i].Version} al posto della {i + 1}."); + } + } + + return ordered; + } + + public static int GetVersion(SqliteConnection connection) => + (int)connection.Command("PRAGMA user_version").ScalarInt64(); + + /// Applies the pending migrations. Returns the resulting version. + public static int Apply(SqliteConnection connection, IReadOnlyList migrations) + { + var current = GetVersion(connection); + var latest = migrations.Count == 0 ? 0 : migrations[^1].Version; + if (current > latest) + { + throw new DatabaseMigrationException( + $"Il database è stato scritto da una versione più recente di Febe (schema {current}; questa versione arriva al {latest}). " + + "Febe non lo modifica: aggiorna il programma oppure ripristina una copia da Dati/copie."); + } + + if (current == latest) + { + return current; + } + + // Table rebuilds in later migrations need foreign keys off; they are checked before each commit instead. + connection.Command("PRAGMA foreign_keys = OFF").ExecuteNonQuery(); + try + { + foreach (var migration in migrations.Where(m => m.Version > current)) + { + using var transaction = connection.BeginTransaction(deferred: false); + try + { + connection.Command(migration.Sql, transaction).ExecuteNonQuery(); + using (var check = connection.Command("PRAGMA foreign_key_check", transaction).ExecuteReader()) + { + if (check.Read()) + { + throw new DatabaseMigrationException( + $"La migrazione {migration.Version} ({migration.Name}) lascia riferimenti non validi nella tabella {check.GetString(0)}."); + } + } + + connection.Command(string.Create(CultureInfo.InvariantCulture, $"PRAGMA user_version = {migration.Version}"), transaction) + .ExecuteNonQuery(); + transaction.Commit(); + } + catch (Exception ex) when (ex is SqliteException or DatabaseMigrationException) + { + transaction.Rollback(); + throw ex as DatabaseMigrationException ?? new DatabaseMigrationException( + $"La migrazione {migration.Version} ({migration.Name}) non è riuscita: il database resta allo schema {GetVersion(connection)}.", + ex); + } + } + } + finally + { + connection.Command("PRAGMA foreign_keys = ON").ExecuteNonQuery(); + } + + return GetVersion(connection); + } +} diff --git a/src/Febe.Data/Migrations/0001_schema.sql b/src/Febe.Data/Migrations/0001_schema.sql new file mode 100644 index 0000000..a3e3a50 --- /dev/null +++ b/src/Febe.Data/Migrations/0001_schema.sql @@ -0,0 +1,291 @@ +-- Febe, schema version 1 (spec §8.3). +-- Times are UTC instants stored as INTEGER Unix milliseconds. Enumerations are stored as their English names. +-- Instagram identifiers are TEXT: numeric today, but no assumption is made on their size or form (rule 10). +-- Run by the migration runner inside a transaction; PRAGMA user_version is set by the runner. + +CREATE TABLE setting ( + key TEXT PRIMARY KEY NOT NULL, + value TEXT NOT NULL +) WITHOUT ROWID; + +CREATE TABLE account ( + id INTEGER PRIMARY KEY, + instagram_id TEXT UNIQUE, + username TEXT NOT NULL COLLATE NOCASE CHECK (length(username) > 0), + display_name TEXT, + is_private INTEGER NOT NULL DEFAULT 0 CHECK (is_private IN (0, 1)), + is_followed INTEGER NOT NULL DEFAULT 0 CHECK (is_followed IN (0, 1)), + is_mine INTEGER NOT NULL DEFAULT 0 CHECK (is_mine IN (0, 1)), + state TEXT NOT NULL, + state_changed_at INTEGER, + unreachable_reason TEXT, + keep_updated INTEGER NOT NULL DEFAULT 1 CHECK (keep_updated IN (0, 1)), + frequency TEXT NOT NULL, + custom_post_interval_min INTEGER CHECK (custom_post_interval_min IS NULL OR custom_post_interval_min > 0), + custom_story_interval_min INTEGER CHECK (custom_story_interval_min IS NULL OR custom_story_interval_min > 0), + content_types INTEGER NOT NULL CHECK (content_types >= 0), + history_depth TEXT NOT NULL, + history_last_posts INTEGER CHECK (history_last_posts IS NULL OR history_last_posts >= 0), + history_from INTEGER, + backfill_posts_per_day INTEGER NOT NULL CHECK (backfill_posts_per_day >= 0), + max_video_bytes INTEGER CHECK (max_video_bytes IS NULL OR max_video_bytes > 0), + story_videos INTEGER NOT NULL DEFAULT 1 CHECK (story_videos IN (0, 1)), + folder TEXT, + backfill_cursor TEXT, + backfill_completed_at INTEGER, + post_count INTEGER, + last_profile_check_at INTEGER, + next_profile_check_at INTEGER, + last_stories_check_at INTEGER, + next_stories_check_at INTEGER, + notices INTEGER NOT NULL DEFAULT 0, + previous_username TEXT, + renamed_at INTEGER, + format_unrecognized_at INTEGER, + added_at INTEGER NOT NULL +); + +CREATE INDEX ix_account_username ON account (username); +CREATE INDEX ix_account_state ON account (state); +-- At most one account is Alberto's own profile («Tu»). +CREATE UNIQUE INDEX ux_account_mine ON account (is_mine) WHERE is_mine = 1; + +CREATE TABLE entry ( + id INTEGER PRIMARY KEY, + account_id INTEGER NOT NULL REFERENCES account (id) ON DELETE CASCADE, + kind TEXT NOT NULL, + instagram_id TEXT, + code TEXT, + published_at INTEGER NOT NULL, + caption TEXT, + author_username TEXT, + author_instagram_id TEXT, + state TEXT NOT NULL, + provenance TEXT NOT NULL, + discovered_at INTEGER NOT NULL, + downloaded_at INTEGER, + deleted_at INTEGER, + expires_at INTEGER, + -- Lowercase text without accents (caption and author), for the search of the library. + search_text TEXT, + UNIQUE (account_id, kind, instagram_id) +); + +CREATE INDEX ix_entry_account_published ON entry (account_id, published_at); +-- The library mosaic: keyset windows by publication time, with the filter columns in the index so that windows, +-- totals and counts per day never visit the table (spec §4.6: fluid with 200,000 entries). +CREATE INDEX ix_entry_library ON entry (published_at, kind, state, account_id, provenance); +CREATE INDEX ix_entry_kind_published ON entry (kind, published_at); +CREATE INDEX ix_entry_state ON entry (state); +-- Accounts list counts and the per-account daily backfill limit, answered from the index alone. +CREATE INDEX ix_entry_account_kind ON entry (account_id, kind, state, discovered_at); + +CREATE TABLE media ( + id INTEGER PRIMARY KEY, + entry_id INTEGER NOT NULL REFERENCES entry (id) ON DELETE CASCADE, + position INTEGER NOT NULL CHECK (position >= 1), + kind TEXT NOT NULL, + instagram_id TEXT, + width INTEGER, + height INTEGER, + duration_ms INTEGER, + state TEXT NOT NULL, + relative_path TEXT, + bytes INTEGER CHECK (bytes IS NULL OR bytes >= 0), + sha256 TEXT CHECK (sha256 IS NULL OR length(sha256) = 64), + phash INTEGER, + has_thumbnail INTEGER NOT NULL DEFAULT 0 CHECK (has_thumbnail IN (0, 1)), + source_url TEXT, + cover_url TEXT, + source_seen_at INTEGER, + attempts INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + downloaded_at INTEGER, + UNIQUE (entry_id, position) +); + +CREATE INDEX ix_media_sha256 ON media (sha256) WHERE sha256 IS NOT NULL; +CREATE INDEX ix_media_phash ON media (phash) WHERE phash IS NOT NULL; +CREATE INDEX ix_media_state ON media (state); + +CREATE TABLE highlight ( + id INTEGER PRIMARY KEY, + account_id INTEGER NOT NULL REFERENCES account (id) ON DELETE CASCADE, + instagram_id TEXT, + title TEXT NOT NULL, + position INTEGER NOT NULL DEFAULT 0, + discovered_at INTEGER NOT NULL, + last_checked_at INTEGER, + removed_at INTEGER, + UNIQUE (account_id, instagram_id) +); + +CREATE INDEX ix_highlight_account_position ON highlight (account_id, position); + +CREATE TABLE highlight_entry ( + highlight_id INTEGER NOT NULL REFERENCES highlight (id) ON DELETE CASCADE, + entry_id INTEGER NOT NULL REFERENCES entry (id) ON DELETE CASCADE, + position INTEGER NOT NULL, + PRIMARY KEY (highlight_id, entry_id) +) WITHOUT ROWID; + +CREATE INDEX ix_highlight_entry_entry ON highlight_entry (entry_id); + +CREATE TABLE task ( + id INTEGER PRIMARY KEY, + kind TEXT NOT NULL, + account_id INTEGER REFERENCES account (id) ON DELETE CASCADE, + due_at INTEGER NOT NULL, + priority INTEGER NOT NULL DEFAULT 0, + state TEXT NOT NULL, + payload TEXT, + is_manual INTEGER NOT NULL DEFAULT 0 CHECK (is_manual IN (0, 1)), + attempts INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + started_at INTEGER, + completed_at INTEGER, + last_error TEXT +); + +CREATE INDEX ix_task_state_due ON task (state, due_at); +CREATE INDEX ix_task_account ON task (account_id); + +CREATE TABLE session ( + id INTEGER PRIMARY KEY, + started_at INTEGER NOT NULL, + ended_at INTEGER, + action_count INTEGER NOT NULL DEFAULT 0, + outcome TEXT NOT NULL, + summary TEXT +); + +CREATE INDEX ix_session_started ON session (started_at); + +CREATE TABLE action_log ( + id INTEGER PRIMARY KEY, + at INTEGER NOT NULL, + category TEXT NOT NULL, + account_id INTEGER REFERENCES account (id) ON DELETE SET NULL, + session_id INTEGER REFERENCES session (id) ON DELETE SET NULL, + amount INTEGER NOT NULL DEFAULT 1 CHECK (amount >= 0) +); + +CREATE INDEX ix_action_log_category_at ON action_log (category, at); +CREATE INDEX ix_action_log_account_at ON action_log (account_id, category, at); +CREATE INDEX ix_action_log_at ON action_log (at); + +CREATE TABLE incident ( + id INTEGER PRIMARY KEY, + at INTEGER NOT NULL, + level TEXT NOT NULL, + signal TEXT NOT NULL, + url TEXT, + stopped_until INTEGER, + resolved_at INTEGER, + session_id INTEGER REFERENCES session (id) ON DELETE SET NULL, + note TEXT +); + +CREATE INDEX ix_incident_at ON incident (at); +CREATE INDEX ix_incident_open ON incident (resolved_at) WHERE resolved_at IS NULL; + +CREATE TABLE event ( + id INTEGER PRIMARY KEY, + at INTEGER NOT NULL, + severity TEXT NOT NULL, + code TEXT NOT NULL, + message TEXT NOT NULL, + account_id INTEGER REFERENCES account (id) ON DELETE SET NULL, + session_id INTEGER REFERENCES session (id) ON DELETE SET NULL +); + +CREATE INDEX ix_event_at ON event (at); +CREATE INDEX ix_event_account ON event (account_id, id); + +CREATE TABLE "following" ( + id INTEGER PRIMARY KEY, + instagram_id TEXT UNIQUE, + username TEXT NOT NULL COLLATE NOCASE, + display_name TEXT, + is_private INTEGER CHECK (is_private IS NULL OR is_private IN (0, 1)), + position INTEGER NOT NULL DEFAULT 0, + read_at INTEGER NOT NULL +); + +CREATE INDEX ix_following_username ON "following" (username); +CREATE INDEX ix_following_position ON "following" (position); + +CREATE TABLE import_run ( + id INTEGER PRIMARY KEY, + source_path TEXT NOT NULL, + source_read_only INTEGER NOT NULL DEFAULT 0 CHECK (source_read_only IN (0, 1)), + mode TEXT NOT NULL, + state TEXT NOT NULL, + started_at INTEGER NOT NULL, + analyzed_at INTEGER, + completed_at INTEGER, + last_error TEXT +); + +CREATE TABLE import_file ( + id INTEGER PRIMARY KEY, + run_id INTEGER NOT NULL REFERENCES import_run (id) ON DELETE CASCADE, + relative_path TEXT NOT NULL, + folder TEXT NOT NULL, + bytes INTEGER NOT NULL DEFAULT 0, + modified_at INTEGER, + media_kind TEXT, + content_type TEXT, + width INTEGER, + height INTEGER, + duration_ms INTEGER, + sha256 TEXT CHECK (sha256 IS NULL OR length(sha256) = 64), + phash INTEGER, + taken_at INTEGER, + date_source TEXT, + instagram_id TEXT, + code TEXT, + probable_account TEXT, + probable_kind TEXT, + highlight_title TEXT, + outcome TEXT NOT NULL, + matched_media_id INTEGER REFERENCES media (id) ON DELETE SET NULL, + target_account_id INTEGER REFERENCES account (id) ON DELETE SET NULL, + decision TEXT NOT NULL, + state TEXT NOT NULL, + entry_id INTEGER REFERENCES entry (id) ON DELETE SET NULL, + destination_path TEXT, + last_error TEXT, + UNIQUE (run_id, relative_path) +); + +CREATE INDEX ix_import_file_run_state ON import_file (run_id, state); +CREATE INDEX ix_import_file_run_folder ON import_file (run_id, folder); +CREATE INDEX ix_import_file_sha256 ON import_file (sha256) WHERE sha256 IS NOT NULL; +-- Foreign keys with ON DELETE actions need an index on the child column, or each parent delete scans the table. +CREATE INDEX ix_import_file_matched_media ON import_file (matched_media_id) WHERE matched_media_id IS NOT NULL; +CREATE INDEX ix_import_file_entry ON import_file (entry_id) WHERE entry_id IS NOT NULL; +CREATE INDEX ix_import_file_target_account ON import_file (target_account_id) WHERE target_account_id IS NOT NULL; + +CREATE TABLE duplicate_pair ( + id INTEGER PRIMARY KEY, + origin TEXT NOT NULL, + reason TEXT NOT NULL, + existing_media_id INTEGER REFERENCES media (id) ON DELETE CASCADE, + existing_import_file_id INTEGER REFERENCES import_file (id) ON DELETE CASCADE, + candidate_media_id INTEGER REFERENCES media (id) ON DELETE CASCADE, + candidate_import_file_id INTEGER REFERENCES import_file (id) ON DELETE CASCADE, + distance INTEGER, + decision TEXT NOT NULL, + created_at INTEGER NOT NULL, + decided_at INTEGER, + -- Exactly one reference per side. + CHECK ((existing_media_id IS NULL) <> (existing_import_file_id IS NULL)), + CHECK ((candidate_media_id IS NULL) <> (candidate_import_file_id IS NULL)) +); + +CREATE INDEX ix_duplicate_pair_decision ON duplicate_pair (decision, id); +CREATE INDEX ix_duplicate_pair_existing_media ON duplicate_pair (existing_media_id); +CREATE INDEX ix_duplicate_pair_candidate_media ON duplicate_pair (candidate_media_id); +CREATE INDEX ix_duplicate_pair_existing_file ON duplicate_pair (existing_import_file_id); +CREATE INDEX ix_duplicate_pair_candidate_file ON duplicate_pair (candidate_import_file_id); diff --git a/src/Febe.Data/Sql.cs b/src/Febe.Data/Sql.cs new file mode 100644 index 0000000..57b0573 --- /dev/null +++ b/src/Febe.Data/Sql.cs @@ -0,0 +1,123 @@ +using System.Globalization; +using Microsoft.Data.Sqlite; + +namespace Febe.Data; + +/// Conversions between domain values and SQLite columns. +internal static class Sql +{ + /// UTC instant → Unix milliseconds. + public static long Time(DateTimeOffset value) => value.ToUnixTimeMilliseconds(); + + public static object Time(DateTimeOffset? value) => value is { } v ? v.ToUnixTimeMilliseconds() : DBNull.Value; + + public static DateTimeOffset ToTime(long ms) => DateTimeOffset.FromUnixTimeMilliseconds(ms); + + public static object Text(string? value) => value is null ? DBNull.Value : value; + + public static object Int(long? value) => value is { } v ? v : DBNull.Value; + + public static object Int(int? value) => value is { } v ? v : DBNull.Value; + + public static object Bool(bool value) => value ? 1L : 0L; + + public static object Bool(bool? value) => value is { } v ? (v ? 1L : 0L) : DBNull.Value; + + public static object Enum(T value) + where T : struct, Enum => value.ToString(); + + public static object Enum(T? value) + where T : struct, Enum => value is { } v ? v.ToString() : DBNull.Value; + + public static object Hash(ulong? value) => value is { } v ? unchecked((long)v) : DBNull.Value; + + public static object Duration(TimeSpan? value) => value is { } v ? (long)v.TotalMilliseconds : DBNull.Value; + + public static object Minutes(TimeSpan? value) => value is { } v ? (long)Math.Round(v.TotalMinutes) : DBNull.Value; + + public static T ParseEnum(string text) + where T : struct, Enum => System.Enum.Parse(text, ignoreCase: false); + + // Reader helpers ----------------------------------------------------------------------------- + + public static string? GetTextOrNull(this SqliteDataReader r, int i) => r.IsDBNull(i) ? null : r.GetString(i); + + public static long? GetInt64OrNull(this SqliteDataReader r, int i) => r.IsDBNull(i) ? null : r.GetInt64(i); + + public static int? GetInt32OrNull(this SqliteDataReader r, int i) => r.IsDBNull(i) ? null : r.GetInt32(i); + + public static bool GetBool(this SqliteDataReader r, int i) => r.GetInt64(i) != 0; + + public static bool? GetBoolOrNull(this SqliteDataReader r, int i) => r.IsDBNull(i) ? null : r.GetInt64(i) != 0; + + public static DateTimeOffset GetTime(this SqliteDataReader r, int i) => ToTime(r.GetInt64(i)); + + public static DateTimeOffset? GetTimeOrNull(this SqliteDataReader r, int i) => r.IsDBNull(i) ? null : ToTime(r.GetInt64(i)); + + public static T GetEnum(this SqliteDataReader r, int i) + where T : struct, Enum => ParseEnum(r.GetString(i)); + + public static T? GetEnumOrNull(this SqliteDataReader r, int i) + where T : struct, Enum => r.IsDBNull(i) ? null : ParseEnum(r.GetString(i)); + + public static ulong? GetHashOrNull(this SqliteDataReader r, int i) => r.IsDBNull(i) ? null : unchecked((ulong)r.GetInt64(i)); + + public static TimeSpan? GetDurationOrNull(this SqliteDataReader r, int i) => + r.IsDBNull(i) ? null : TimeSpan.FromMilliseconds(r.GetInt64(i)); + + public static TimeSpan? GetMinutesOrNull(this SqliteDataReader r, int i) => + r.IsDBNull(i) ? null : TimeSpan.FromMinutes(r.GetInt64(i)); + + // Command helpers ---------------------------------------------------------------------------- + + public static SqliteCommand Command(this SqliteConnection connection, string sql, SqliteTransaction? transaction = null) + { + var command = connection.CreateCommand(); + command.CommandText = sql; + command.Transaction = transaction; + return command; + } + + /// Sets a parameter, adding it the first time: a prepared command can be run again with new values. + public static SqliteCommand With(this SqliteCommand command, string name, object? value) + { + if (command.Parameters.Contains(name)) + { + command.Parameters[name].Value = value ?? DBNull.Value; + } + else + { + command.Parameters.AddWithValue(name, value ?? DBNull.Value); + } + + return command; + } + + /// Adds parameters @p0, @p1, ... and returns the comma-separated list of their names, for IN (...). + public static string AddList(this SqliteCommand command, string prefix, IEnumerable values) + { + var names = new List(); + var i = 0; + foreach (var value in values) + { + var name = string.Create(CultureInfo.InvariantCulture, $"@{prefix}{i++}"); + command.Parameters.AddWithValue(name, (object?)value ?? DBNull.Value); + names.Add(name); + } + + return names.Count == 0 ? "NULL" : string.Join(", ", names); + } + + public static long ScalarInt64(this SqliteCommand command) + { + var value = command.ExecuteScalar(); + return value is null or DBNull ? 0 : Convert.ToInt64(value, CultureInfo.InvariantCulture); + } + + /// True for SQLITE_CONSTRAINT errors (unique, check, foreign key, not null). + public static bool IsConstraintViolation(this SqliteException exception) => exception.SqliteErrorCode == 19; + + /// True for a UNIQUE or PRIMARY KEY constraint violation. + public static bool IsUniqueViolation(this SqliteException exception) => + exception.SqliteErrorCode == 19 && exception.SqliteExtendedErrorCode is 2067 or 1555; +} diff --git a/src/Febe.Data/SqliteWriter.cs b/src/Febe.Data/SqliteWriter.cs new file mode 100644 index 0000000..e4147f3 --- /dev/null +++ b/src/Febe.Data/SqliteWriter.cs @@ -0,0 +1,324 @@ +using System.Threading.Channels; +using Microsoft.Data.Sqlite; + +namespace Febe.Data; + +/// +/// The active transaction of the writer, passed to each write. Commands are prepared once per batch and reused +/// (same SQL text, new parameter values), then disposed when the batch ends. +/// +internal sealed class WriteContext(SqliteConnection connection, SqliteTransaction transaction) : IDisposable +{ + private readonly Dictionary _commands = new(StringComparer.Ordinal); + + public SqliteConnection Connection { get; } = connection; + + public SqliteTransaction Transaction { get; } = transaction; + + /// + /// The prepared command for this SQL in the current batch. Callers set every parameter they use (see + /// ) and close readers before running the same SQL again. + /// + public SqliteCommand Command(string sql) + { + if (!_commands.TryGetValue(sql, out var command)) + { + command = Connection.Command(sql, Transaction); + _commands[sql] = command; + } + + return command; + } + + public long LastInsertRowId() => Command("SELECT last_insert_rowid()").ScalarInt64(); + + public void Dispose() + { + foreach (var command in _commands.Values) + { + command.Dispose(); + } + + _commands.Clear(); + } +} + +/// +/// The single writer of the database (spec §8.3: «Un solo scrittore: le scritture passano da una coda»). +/// +/// Every write is queued on a channel and executed by one dedicated thread on one dedicated connection. Writes that +/// are queued together share one transaction (group commit), each inside its own savepoint: a failing write is rolled +/// back alone and reports its exception; the others commit. A write's task completes only after the commit. +/// +/// +internal sealed class SqliteWriter : IDisposable +{ + private const int MaxBatch = 64; + private const string Savepoint = "febe_write"; + + private readonly SqliteConnection _connection; + private readonly Channel _queue = Channel.CreateUnbounded(new UnboundedChannelOptions + { + SingleReader = true, + SingleWriter = false, + AllowSynchronousContinuations = false, + }); + + private readonly Thread _thread; + private int _executing; + private int _maxObservedConcurrency; + private int _disposed; + + public SqliteWriter(SqliteConnection connection) + { + _connection = connection; + _thread = new Thread(Run) + { + IsBackground = true, + Name = "Febe database writer", + }; + _thread.Start(); + } + + /// Highest number of writes seen executing at the same time (always 1): checked by the tests. + internal int MaxObservedConcurrency => Volatile.Read(ref _maxObservedConcurrency); + + /// The managed thread id of the writer thread. + internal int ThreadId => _thread.ManagedThreadId; + + public Task ExecuteAsync(Func work, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(work); + if (ct.IsCancellationRequested) + { + return Task.FromCanceled(ct); + } + + var item = new WorkItem(work, ct); + if (!_queue.Writer.TryWrite(item)) + { + item.Dispose(); + return Task.FromException(new ObjectDisposedException(nameof(SqliteWriter), "Il database è chiuso.")); + } + + return item.Task; + } + + public Task ExecuteAsync(Action work, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(work); + return ExecuteAsync( + context => + { + work(context); + return true; + }, + ct); + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _queue.Writer.TryComplete(); + _thread.Join(); + } + + private void Run() + { + var reader = _queue.Reader; + var batch = new List(MaxBatch); + while (true) + { + bool more; + try + { + more = reader.WaitToReadAsync().AsTask().GetAwaiter().GetResult(); + } + catch (ChannelClosedException) + { + more = false; + } + + if (!more) + { + return; + } + + batch.Clear(); + while (batch.Count < MaxBatch && reader.TryRead(out var item)) + { + batch.Add(item); + } + + ProcessBatch(batch); + } + } + + private void ProcessBatch(List batch) + { + var started = new List(batch.Count); + foreach (var item in batch) + { + if (item.TryStart()) + { + started.Add(item); + } + else + { + item.Dispose(); // cancelled while queued + } + } + + if (started.Count == 0) + { + return; + } + + var succeeded = new List(started.Count); + SqliteTransaction? transaction = null; + WriteContext? context = null; + try + { + transaction = _connection.BeginTransaction(deferred: false); + context = new WriteContext(_connection, transaction); + foreach (var item in started) + { + transaction.Save(Savepoint); + var executing = Interlocked.Increment(ref _executing); + UpdateMax(executing); + try + { + item.Execute(context); + transaction.Release(Savepoint); + succeeded.Add(item); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + transaction.Rollback(Savepoint); + transaction.Release(Savepoint); + item.Fail(ex); + } + finally + { + Interlocked.Decrement(ref _executing); + } + } + + transaction.Commit(); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + try + { + transaction?.Rollback(); + } + catch (SqliteException) + { + // The transaction may already be gone; the original error is what matters. + } + catch (InvalidOperationException) + { + } + + foreach (var item in started) + { + item.Fail(ex); // no effect on items that already failed on their own + } + + return; + } + finally + { + context?.Dispose(); + transaction?.Dispose(); + } + + foreach (var item in succeeded) + { + item.Complete(); + } + } + + private void UpdateMax(int executing) + { + int seen; + while (executing > (seen = Volatile.Read(ref _maxObservedConcurrency))) + { + if (Interlocked.CompareExchange(ref _maxObservedConcurrency, executing, seen) == seen) + { + return; + } + } + } + + private abstract class WorkItem : IDisposable + { + private const int Queued = 0; + private const int Started = 1; + private const int Cancelled = 2; + + private readonly CancellationTokenRegistration _registration; + private int _state; + + protected WorkItem(CancellationToken ct) + { + if (ct.CanBeCanceled) + { + _registration = ct.Register(static s => ((WorkItem)s!).OnCancel(), this); + } + + CancellationToken = ct; + } + + protected CancellationToken CancellationToken { get; } + + /// Queued → started. False when the caller cancelled first. + public bool TryStart() => Interlocked.CompareExchange(ref _state, Started, Queued) == Queued; + + public abstract void Execute(WriteContext context); + + public abstract void Complete(); + + public abstract void Fail(Exception exception); + + public void Dispose() => _registration.Dispose(); + + protected abstract void SetCancelled(); + + private void OnCancel() + { + if (Interlocked.CompareExchange(ref _state, Cancelled, Queued) == Queued) + { + SetCancelled(); + } + } + } + + private sealed class WorkItem(Func work, CancellationToken ct) : WorkItem(ct) + { + private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously); + private T _result = default!; + + public Task Task => _completion.Task; + + public override void Execute(WriteContext context) => _result = work(context); + + public override void Complete() + { + Dispose(); + _completion.TrySetResult(_result); + } + + public override void Fail(Exception exception) + { + Dispose(); + _completion.TrySetException(exception); + } + + protected override void SetCancelled() => _completion.TrySetCanceled(CancellationToken); + } +} diff --git a/src/Febe.Data/Stores/AccountStore.cs b/src/Febe.Data/Stores/AccountStore.cs new file mode 100644 index 0000000..e397688 --- /dev/null +++ b/src/Febe.Data/Stores/AccountStore.cs @@ -0,0 +1,459 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; +using Microsoft.Data.Sqlite; + +namespace Febe.Data.Stores; + +internal sealed class AccountStore(FebeDatabase db) : IAccountStore +{ + internal const string Columns = + "a.id, a.instagram_id, a.username, a.display_name, a.is_private, a.is_followed, a.is_mine, a.state, a.state_changed_at, " + + "a.unreachable_reason, a.keep_updated, a.frequency, a.custom_post_interval_min, a.custom_story_interval_min, a.content_types, " + + "a.history_depth, a.history_last_posts, a.history_from, a.backfill_posts_per_day, a.max_video_bytes, a.story_videos, a.folder, " + + "a.backfill_cursor, a.backfill_completed_at, a.post_count, a.last_profile_check_at, a.next_profile_check_at, " + + "a.last_stories_check_at, a.next_stories_check_at, a.notices, a.previous_username, a.renamed_at, a.format_unrecognized_at, a.added_at"; + + internal const int ColumnCount = 34; + + private static readonly string Visible = string.Join(", ", EntryStateRules.Visible.Select(s => $"'{s}'")); + + internal static Account Read(SqliteDataReader r, int o = 0) => new() + { + Id = r.GetInt64(o), + InstagramId = r.GetTextOrNull(o + 1), + Username = r.GetString(o + 2), + DisplayName = r.GetTextOrNull(o + 3), + IsPrivate = r.GetBool(o + 4), + IsFollowed = r.GetBool(o + 5), + IsMine = r.GetBool(o + 6), + State = r.GetEnum(o + 7), + StateChangedAt = r.GetTimeOrNull(o + 8), + UnreachableReason = r.GetEnumOrNull(o + 9), + KeepUpdated = r.GetBool(o + 10), + Frequency = r.GetEnum(o + 11), + CustomPostInterval = r.GetMinutesOrNull(o + 12), + CustomStoryInterval = r.GetMinutesOrNull(o + 13), + ContentTypes = (ContentTypes)r.GetInt32(o + 14), + Limits = new AccountLimits + { + Depth = r.GetEnum(o + 15), + LastPosts = r.GetInt32OrNull(o + 16), + FromDate = r.GetTimeOrNull(o + 17), + BackfillPostsPerDay = r.GetInt32(o + 18), + MaxVideoBytes = r.GetInt64OrNull(o + 19), + StoryVideos = r.GetBool(o + 20), + }, + Folder = r.GetTextOrNull(o + 21), + BackfillCursor = r.GetTextOrNull(o + 22), + BackfillCompletedAt = r.GetTimeOrNull(o + 23), + PostCount = r.GetInt32OrNull(o + 24), + LastProfileCheckAt = r.GetTimeOrNull(o + 25), + NextProfileCheckAt = r.GetTimeOrNull(o + 26), + LastStoriesCheckAt = r.GetTimeOrNull(o + 27), + NextStoriesCheckAt = r.GetTimeOrNull(o + 28), + Notices = (AccountNotices)r.GetInt32(o + 29), + PreviousUsername = r.GetTextOrNull(o + 30), + RenamedAt = r.GetTimeOrNull(o + 31), + FormatUnrecognizedAt = r.GetTimeOrNull(o + 32), + AddedAt = r.GetTime(o + 33), + }; + + private static void Bind(SqliteCommand c, Account a) + { + c.With("@instagram_id", Sql.Text(Normalize(a.InstagramId))) + .With("@username", NormalizeUsername(a.Username)) + .With("@display_name", Sql.Text(a.DisplayName)) + .With("@is_private", Sql.Bool(a.IsPrivate)) + .With("@is_followed", Sql.Bool(a.IsFollowed)) + .With("@is_mine", Sql.Bool(a.IsMine)) + .With("@state", Sql.Enum(a.State)) + .With("@state_changed_at", Sql.Time(a.StateChangedAt)) + .With("@unreachable_reason", Sql.Enum(a.UnreachableReason)) + .With("@keep_updated", Sql.Bool(a.KeepUpdated)) + .With("@frequency", Sql.Enum(a.Frequency)) + .With("@custom_post_interval_min", Sql.Minutes(a.CustomPostInterval)) + .With("@custom_story_interval_min", Sql.Minutes(a.CustomStoryInterval)) + .With("@content_types", (long)a.ContentTypes) + .With("@history_depth", Sql.Enum(a.Limits.Depth)) + .With("@history_last_posts", Sql.Int(a.Limits.LastPosts)) + .With("@history_from", Sql.Time(a.Limits.FromDate)) + .With("@backfill_posts_per_day", (long)a.Limits.BackfillPostsPerDay) + .With("@max_video_bytes", Sql.Int(a.Limits.MaxVideoBytes)) + .With("@story_videos", Sql.Bool(a.Limits.StoryVideos)) + .With("@folder", Sql.Text(a.Folder)) + .With("@backfill_cursor", Sql.Text(a.BackfillCursor)) + .With("@backfill_completed_at", Sql.Time(a.BackfillCompletedAt)) + .With("@post_count", Sql.Int(a.PostCount)) + .With("@last_profile_check_at", Sql.Time(a.LastProfileCheckAt)) + .With("@next_profile_check_at", Sql.Time(a.NextProfileCheckAt)) + .With("@last_stories_check_at", Sql.Time(a.LastStoriesCheckAt)) + .With("@next_stories_check_at", Sql.Time(a.NextStoriesCheckAt)) + .With("@notices", (long)a.Notices) + .With("@previous_username", Sql.Text(a.PreviousUsername)) + .With("@renamed_at", Sql.Time(a.RenamedAt)) + .With("@format_unrecognized_at", Sql.Time(a.FormatUnrecognizedAt)) + .With("@added_at", Sql.Time(a.AddedAt)); + } + + private static string? Normalize(string? instagramId) => string.IsNullOrWhiteSpace(instagramId) ? null : instagramId.Trim(); + + private static string NormalizeUsername(string username) => username.Trim().TrimStart('@'); + + private static void Validate(Account account) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentException.ThrowIfNullOrWhiteSpace(account.Username); + if (account.Limits.BackfillPostsPerDay < 0) + { + throw new ArgumentException("Il massimo di storico al giorno non può essere negativo.", nameof(account)); + } + + if (account.Frequency == Frequency.Custom && (account.CustomPostInterval is null || account.CustomStoryInterval is null)) + { + throw new ArgumentException("Con la frequenza «Su misura» servono i due intervalli.", nameof(account)); + } + } + + public Task GetAsync(long accountId, CancellationToken ct = default) => + db.ReadAsync(c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.id = @id").With("@id", accountId)), ct); + + public Task FindByInstagramIdAsync(string instagramId, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(instagramId); + return db.ReadAsync( + c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.instagram_id = @id").With("@id", instagramId.Trim())), + ct); + } + + public Task FindByUsernameAsync(string username, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(username); + var name = username.Trim().TrimStart('@'); + return db.ReadAsync( + c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.username = @u ORDER BY a.id LIMIT 1").With("@u", name)), + ct); + } + + public Task GetMineAsync(CancellationToken ct = default) => + db.ReadAsync(c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.is_mine = 1")), ct); + + public Task> ListAsync(CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var r = c.Command($"SELECT {Columns} FROM account a ORDER BY a.username, a.id").ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(Read(r)); + } + + return list; + }, + ct); + + public Task> ListSummariesAsync(DateTimeOffset newSince, CancellationToken ct = default) => + db.ReadAsync>( + c => + { + // One pass over the (account, kind, state, discovered) index for every account at once. + var counts = new Dictionary(); + var sql = $""" + SELECT e.account_id, + SUM(e.kind <> 'ProfilePicture' AND e.state IN ({Visible})), + SUM(e.kind = 'Post' AND e.state IN ({Visible})), + SUM(e.kind = 'Post' AND e.discovered_at >= @since), + SUM(e.kind = 'Story' AND e.discovered_at >= @since) + FROM entry e GROUP BY e.account_id + """; + using (var r = c.Command(sql).With("@since", Sql.Time(newSince)).ExecuteReader()) + { + while (r.Read()) + { + counts[r.GetInt64(0)] = (r.GetInt32(1), r.GetInt32(2), r.GetInt32(3), r.GetInt32(4)); + } + } + + using var accounts = c.Command($"SELECT {Columns} FROM account a ORDER BY a.username, a.id").ExecuteReader(); + var list = new List(); + while (accounts.Read()) + { + var account = Read(accounts); + var (entries, posts, newPosts, newStories) = counts.GetValueOrDefault(account.Id); + list.Add(new AccountSummary(account, entries, posts, newPosts, newStories)); + } + + return list; + }, + ct); + + public Task GetStatsAsync(long accountId, CancellationToken ct = default) => + db.ReadAsync( + c => + { + var sql = $""" + SELECT e.kind, COUNT(*), MAX(e.published_at) FROM entry e + WHERE e.account_id = @a AND e.state IN ({Visible}) GROUP BY e.kind + """; + var stats = new AccountStats { AccountId = accountId }; + DateTimeOffset? last = null; + using (var r = c.Command(sql).With("@a", accountId).ExecuteReader()) + { + while (r.Read()) + { + var kind = r.GetEnum(0); + var count = r.GetInt32(1); + var max = r.GetTimeOrNull(2); + stats = kind switch + { + EntryKind.Post => stats with { Posts = count }, + EntryKind.Story => stats with { Stories = count }, + EntryKind.Highlight => stats with { HighlightItems = count }, + EntryKind.Tagged => stats with { Tagged = count }, + EntryKind.ProfilePicture => stats with { ProfilePictures = count }, + _ => stats, + }; + if (kind != EntryKind.ProfilePicture && max is { } m && (last is null || m > last)) + { + last = m; + } + } + } + + var bytes = c.Command(""" + SELECT COALESCE(SUM(m.bytes), 0) FROM media m JOIN entry e ON e.id = m.entry_id + WHERE e.account_id = @a AND m.state IN ('Downloaded', 'Imported') + """).With("@a", accountId).ScalarInt64(); + var pending = c.Command(""" + SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id + WHERE e.account_id = @a AND m.state IN ('ToDownload', 'Expired') + """).With("@a", accountId).ScalarInt64(); + var collections = c.Command("SELECT COUNT(*) FROM highlight WHERE account_id = @a AND removed_at IS NULL") + .With("@a", accountId).ScalarInt64(); + + return stats with + { + EntriesInLibrary = stats.Posts + stats.Stories + stats.HighlightItems + stats.Tagged, + Bytes = bytes, + PendingFiles = (int)pending, + HighlightCollections = (int)collections, + LastPublishedAt = last, + }; + }, + ct); + + public Task AddAsync(Account account, CancellationToken ct = default) + { + Validate(account); + return db.WriteAsync( + w => + { + var c = w.Command(""" + INSERT INTO account (instagram_id, username, display_name, is_private, is_followed, is_mine, state, state_changed_at, + unreachable_reason, keep_updated, frequency, custom_post_interval_min, custom_story_interval_min, content_types, + history_depth, history_last_posts, history_from, backfill_posts_per_day, max_video_bytes, story_videos, folder, + backfill_cursor, backfill_completed_at, post_count, last_profile_check_at, next_profile_check_at, + last_stories_check_at, next_stories_check_at, notices, previous_username, renamed_at, format_unrecognized_at, added_at) + VALUES (@instagram_id, @username, @display_name, @is_private, @is_followed, @is_mine, @state, @state_changed_at, + @unreachable_reason, @keep_updated, @frequency, @custom_post_interval_min, @custom_story_interval_min, @content_types, + @history_depth, @history_last_posts, @history_from, @backfill_posts_per_day, @max_video_bytes, @story_videos, @folder, + @backfill_cursor, @backfill_completed_at, @post_count, @last_profile_check_at, @next_profile_check_at, + @last_stories_check_at, @next_stories_check_at, @notices, @previous_username, @renamed_at, @format_unrecognized_at, @added_at) + """); + Bind(c, account); + try + { + c.ExecuteNonQuery(); + } + catch (SqliteException ex) when (ex.IsUniqueViolation()) + { + throw new DuplicateRecordException( + account.IsMine + ? "Esiste già un account con lo stesso identificativo Instagram, oppure il profilo «Tu» è già presente." + : "Esiste già un account con lo stesso identificativo Instagram.", + ex); + } + + return account with { Id = w.LastInsertRowId(), InstagramId = Normalize(account.InstagramId), Username = NormalizeUsername(account.Username) }; + }, + ct); + } + + public Task UpdateAsync(Account account, CancellationToken ct = default) + { + Validate(account); + return db.WriteAsync( + w => + { + var c = w.Command(""" + UPDATE account SET instagram_id = @instagram_id, username = @username, display_name = @display_name, + is_private = @is_private, is_followed = @is_followed, is_mine = @is_mine, state = @state, state_changed_at = @state_changed_at, + unreachable_reason = @unreachable_reason, keep_updated = @keep_updated, frequency = @frequency, + custom_post_interval_min = @custom_post_interval_min, custom_story_interval_min = @custom_story_interval_min, + content_types = @content_types, history_depth = @history_depth, history_last_posts = @history_last_posts, + history_from = @history_from, backfill_posts_per_day = @backfill_posts_per_day, max_video_bytes = @max_video_bytes, + story_videos = @story_videos, folder = @folder, backfill_cursor = @backfill_cursor, + backfill_completed_at = @backfill_completed_at, post_count = @post_count, + last_profile_check_at = @last_profile_check_at, next_profile_check_at = @next_profile_check_at, + last_stories_check_at = @last_stories_check_at, next_stories_check_at = @next_stories_check_at, notices = @notices, + previous_username = @previous_username, renamed_at = @renamed_at, format_unrecognized_at = @format_unrecognized_at, + added_at = @added_at + WHERE id = @id + """); + Bind(c, account); + c.With("@id", account.Id); + try + { + RequireOne(c.ExecuteNonQuery(), account.Id); + } + catch (SqliteException ex) when (ex.IsUniqueViolation()) + { + throw new DuplicateRecordException("Esiste già un account con lo stesso identificativo Instagram, oppure il profilo «Tu» è già presente.", ex); + } + }, + ct); + } + + public Task SetStateAsync(long accountId, AccountState state, DateTimeOffset at, UnreachableReason? reason = null, CancellationToken ct = default) => + db.WriteAsync( + w => RequireOne( + w.Command(""" + UPDATE account SET state = @state, unreachable_reason = @reason, + state_changed_at = CASE WHEN state = @state THEN state_changed_at ELSE @at END + WHERE id = @id + """) + .With("@state", Sql.Enum(state)) + .With("@reason", state == AccountState.Unreachable ? Sql.Enum(reason) : DBNull.Value) + .With("@at", Sql.Time(at)) + .With("@id", accountId) + .ExecuteNonQuery(), + accountId), + ct); + + public Task UpdateChecksAsync(long accountId, AccountCheckTimes times, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(times); + return db.WriteAsync( + w => RequireOne( + w.Command(""" + UPDATE account SET + last_profile_check_at = COALESCE(@lp, last_profile_check_at), + next_profile_check_at = COALESCE(@np, next_profile_check_at), + last_stories_check_at = COALESCE(@ls, last_stories_check_at), + next_stories_check_at = COALESCE(@ns, next_stories_check_at), + post_count = COALESCE(@pc, post_count), + is_private = COALESCE(@pr, is_private), + is_followed = COALESCE(@fo, is_followed), + display_name = COALESCE(@dn, display_name) + WHERE id = @id + """) + .With("@lp", Sql.Time(times.LastProfileCheckAt)) + .With("@np", Sql.Time(times.NextProfileCheckAt)) + .With("@ls", Sql.Time(times.LastStoriesCheckAt)) + .With("@ns", Sql.Time(times.NextStoriesCheckAt)) + .With("@pc", Sql.Int(times.PostCount)) + .With("@pr", Sql.Bool(times.IsPrivate)) + .With("@fo", Sql.Bool(times.IsFollowed)) + .With("@dn", Sql.Text(times.DisplayName)) + .With("@id", accountId) + .ExecuteNonQuery(), + accountId), + ct); + } + + public Task SetBackfillAsync(long accountId, string? cursor, DateTimeOffset? completedAt, CancellationToken ct = default) => + db.WriteAsync( + w => RequireOne( + w.Command("UPDATE account SET backfill_cursor = @c, backfill_completed_at = @d WHERE id = @id") + .With("@c", Sql.Text(cursor)) + .With("@d", Sql.Time(completedAt)) + .With("@id", accountId) + .ExecuteNonQuery(), + accountId), + ct); + + public Task RenameAsync(long accountId, string newUsername, DateTimeOffset at, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(newUsername); + var name = newUsername.Trim().TrimStart('@'); + return db.WriteAsync( + w => + { + string? oldName; + using (var r = w.Command("SELECT username, folder FROM account WHERE id = @id").With("@id", accountId).ExecuteReader()) + { + if (!r.Read()) + { + throw new KeyNotFoundException($"Account {accountId} non trovato."); + } + + oldName = r.GetString(0); + } + + if (string.Equals(oldName, name, StringComparison.Ordinal)) + { + return; + } + + // A default folder follows the user name: pin it to the old name so the folder is kept (spec §4.2). + w.Command(""" + UPDATE account SET folder = COALESCE(folder, @pinned), previous_username = username, username = @u, + renamed_at = @at, notices = notices | @renamed + WHERE id = @id + """) + .With("@pinned", WindowsFileNames.SanitizeSegment(oldName)) + .With("@u", name) + .With("@at", Sql.Time(at)) + .With("@renamed", (long)AccountNotices.Renamed) + .With("@id", accountId) + .ExecuteNonQuery(); + }, + ct); + } + + public Task AddNoticesAsync(long accountId, AccountNotices notices, DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => RequireOne( + w.Command(""" + UPDATE account SET notices = notices | @n, + format_unrecognized_at = CASE WHEN (@n & @uf) <> 0 THEN @at ELSE format_unrecognized_at END, + renamed_at = CASE WHEN (@n & @rn) <> 0 THEN @at ELSE renamed_at END + WHERE id = @id + """) + .With("@n", (long)notices) + .With("@uf", (long)AccountNotices.UnrecognizedFormat) + .With("@rn", (long)AccountNotices.Renamed) + .With("@at", Sql.Time(at)) + .With("@id", accountId) + .ExecuteNonQuery(), + accountId), + ct); + + public Task ClearNoticesAsync(long accountId, AccountNotices notices, CancellationToken ct = default) => + db.WriteAsync( + w => RequireOne( + w.Command("UPDATE account SET notices = notices & ~@n WHERE id = @id") + .With("@n", (long)notices) + .With("@id", accountId) + .ExecuteNonQuery(), + accountId), + ct); + + public Task DeleteAsync(long accountId, CancellationToken ct = default) => + db.WriteAsync(w => w.Command("DELETE FROM account WHERE id = @id").With("@id", accountId).ExecuteNonQuery(), ct); + + private static Account? ReadOne(SqliteCommand command) + { + using var r = command.ExecuteReader(); + return r.Read() ? Read(r) : null; + } + + private static void RequireOne(int rows, long accountId) + { + if (rows == 0) + { + throw new KeyNotFoundException($"Account {accountId} non trovato."); + } + } +} diff --git a/src/Febe.Data/Stores/DuplicateStore.cs b/src/Febe.Data/Stores/DuplicateStore.cs new file mode 100644 index 0000000..a62d75a --- /dev/null +++ b/src/Febe.Data/Stores/DuplicateStore.cs @@ -0,0 +1,111 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; +using Microsoft.Data.Sqlite; + +namespace Febe.Data.Stores; + +internal sealed class DuplicateStore(FebeDatabase db) : IDuplicateStore +{ + private const string Columns = + "id, origin, reason, existing_media_id, existing_import_file_id, candidate_media_id, candidate_import_file_id, distance, decision, created_at, decided_at"; + + private static DuplicatePair Read(SqliteDataReader r) => new() + { + Id = r.GetInt64(0), + Origin = r.GetEnum(1), + Reason = r.GetEnum(2), + ExistingMediaId = r.GetInt64OrNull(3), + ExistingImportFileId = r.GetInt64OrNull(4), + CandidateMediaId = r.GetInt64OrNull(5), + CandidateImportFileId = r.GetInt64OrNull(6), + Distance = r.GetInt32OrNull(7), + Decision = r.GetEnum(8), + CreatedAt = r.GetTime(9), + DecidedAt = r.GetTimeOrNull(10), + }; + + private static List ReadAll(SqliteCommand command) + { + using var r = command.ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(Read(r)); + } + + return list; + } + + public Task AddAsync(DuplicatePair pair, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(pair); + if ((pair.ExistingMediaId is null) == (pair.ExistingImportFileId is null) + || (pair.CandidateMediaId is null) == (pair.CandidateImportFileId is null)) + { + throw new ArgumentException("Ogni lato di una coppia di doppioni è un file della libreria oppure un file dell'importazione, non entrambi.", nameof(pair)); + } + + return db.WriteAsync( + w => + { + var existing = ReadAll(w.Command($""" + SELECT {Columns} FROM duplicate_pair WHERE decision = 'Pending' + AND existing_media_id IS @em AND existing_import_file_id IS @ef + AND candidate_media_id IS @cm AND candidate_import_file_id IS @cf + LIMIT 1 + """) + .With("@em", Sql.Int(pair.ExistingMediaId)).With("@ef", Sql.Int(pair.ExistingImportFileId)) + .With("@cm", Sql.Int(pair.CandidateMediaId)).With("@cf", Sql.Int(pair.CandidateImportFileId))); + if (existing.Count > 0) + { + return existing[0]; + } + + w.Command(""" + INSERT INTO duplicate_pair (origin, reason, existing_media_id, existing_import_file_id, candidate_media_id, + candidate_import_file_id, distance, decision, created_at, decided_at) + VALUES (@o, @r, @em, @ef, @cm, @cf, @d, @dec, @c, @dd) + """) + .With("@o", Sql.Enum(pair.Origin)).With("@r", Sql.Enum(pair.Reason)) + .With("@em", Sql.Int(pair.ExistingMediaId)).With("@ef", Sql.Int(pair.ExistingImportFileId)) + .With("@cm", Sql.Int(pair.CandidateMediaId)).With("@cf", Sql.Int(pair.CandidateImportFileId)) + .With("@d", Sql.Int(pair.Distance)).With("@dec", Sql.Enum(pair.Decision)) + .With("@c", Sql.Time(pair.CreatedAt)).With("@dd", Sql.Time(pair.DecidedAt)) + .ExecuteNonQuery(); + return pair with { Id = w.LastInsertRowId() }; + }, + ct); + } + + public Task GetAsync(long pairId, CancellationToken ct = default) => + db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM duplicate_pair WHERE id = @id").With("@id", pairId)).FirstOrDefault(), ct); + + public Task> ListPendingAsync(DuplicateOrigin? origin = null, long afterId = 0, int limit = 200, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll(c.Command($""" + SELECT {Columns} FROM duplicate_pair WHERE decision = 'Pending' AND id > @after AND (@o IS NULL OR origin = @o) + ORDER BY id LIMIT @limit + """).With("@after", afterId).With("@o", Sql.Enum(origin)).With("@limit", (long)Math.Clamp(limit, 1, 10_000))), + ct); + + public Task CountPendingAsync(DuplicateOrigin? origin = null, CancellationToken ct = default) => + db.ReadAsync( + c => (int)c.Command("SELECT COUNT(*) FROM duplicate_pair WHERE decision = 'Pending' AND (@o IS NULL OR origin = @o)") + .With("@o", Sql.Enum(origin)).ScalarInt64(), + ct); + + public Task DecideAsync(long pairId, DuplicateDecision decision, DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => + { + if (w.Command("UPDATE duplicate_pair SET decision = @d, decided_at = @at WHERE id = @id") + .With("@d", Sql.Enum(decision)) + .With("@at", decision == DuplicateDecision.Pending ? DBNull.Value : Sql.Time(at)) + .With("@id", pairId) + .ExecuteNonQuery() == 0) + { + throw new KeyNotFoundException($"Coppia {pairId} non trovata."); + } + }, + ct); +} diff --git a/src/Febe.Data/Stores/EngineStores.cs b/src/Febe.Data/Stores/EngineStores.cs new file mode 100644 index 0000000..f85cac0 --- /dev/null +++ b/src/Febe.Data/Stores/EngineStores.cs @@ -0,0 +1,635 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Storage; +using Microsoft.Data.Sqlite; + +namespace Febe.Data.Stores; + +internal sealed class TaskStore(FebeDatabase db) : ITaskStore +{ + private const string Columns = + "id, kind, account_id, due_at, priority, state, payload, is_manual, attempts, created_at, started_at, completed_at, last_error"; + + private static EngineTask Read(SqliteDataReader r) => new() + { + Id = r.GetInt64(0), + Kind = r.GetEnum(1), + AccountId = r.GetInt64OrNull(2), + DueAt = r.GetTime(3), + Priority = r.GetInt32(4), + State = r.GetEnum(5), + Payload = r.GetTextOrNull(6), + IsManual = r.GetBool(7), + Attempts = r.GetInt32(8), + CreatedAt = r.GetTime(9), + StartedAt = r.GetTimeOrNull(10), + CompletedAt = r.GetTimeOrNull(11), + LastError = r.GetTextOrNull(12), + }; + + private static List ReadAll(SqliteCommand command) + { + using var r = command.ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(Read(r)); + } + + return list; + } + + public Task EnqueueAsync(EngineTask task, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(task); + return db.WriteAsync( + w => + { + var existing = ReadAll(w.Command($""" + SELECT {Columns} FROM task WHERE state = 'Pending' AND kind = @k AND account_id IS @a AND payload IS @p + ORDER BY id LIMIT 1 + """).With("@k", Sql.Enum(task.Kind)).With("@a", Sql.Int(task.AccountId)).With("@p", Sql.Text(task.Payload))); + if (existing.Count > 0) + { + var current = existing[0]; + var merged = current with + { + DueAt = task.DueAt < current.DueAt ? task.DueAt : current.DueAt, + Priority = Math.Max(task.Priority, current.Priority), + IsManual = current.IsManual || task.IsManual, + }; + w.Command("UPDATE task SET due_at = @d, priority = @p, is_manual = @m WHERE id = @id") + .With("@d", Sql.Time(merged.DueAt)).With("@p", (long)merged.Priority).With("@m", Sql.Bool(merged.IsManual)) + .With("@id", current.Id).ExecuteNonQuery(); + return merged; + } + + w.Command(""" + INSERT INTO task (kind, account_id, due_at, priority, state, payload, is_manual, attempts, created_at, started_at, completed_at, last_error) + VALUES (@k, @a, @d, @p, 'Pending', @pl, @m, @at, @c, NULL, NULL, NULL) + """) + .With("@k", Sql.Enum(task.Kind)).With("@a", Sql.Int(task.AccountId)).With("@d", Sql.Time(task.DueAt)) + .With("@p", (long)task.Priority).With("@pl", Sql.Text(task.Payload)).With("@m", Sql.Bool(task.IsManual)) + .With("@at", (long)task.Attempts).With("@c", Sql.Time(task.CreatedAt)) + .ExecuteNonQuery(); + return task with { Id = w.LastInsertRowId(), State = EngineTaskState.Pending, StartedAt = null, CompletedAt = null, LastError = null }; + }, + ct); + } + + public Task GetAsync(long taskId, CancellationToken ct = default) => + db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM task WHERE id = @id").With("@id", taskId)).FirstOrDefault(), ct); + + public Task> PeekDueAsync(DateTimeOffset now, int limit, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll(c.Command($""" + SELECT {Columns} FROM task WHERE state = 'Pending' AND due_at <= @now + ORDER BY priority DESC, due_at, id LIMIT @limit + """).With("@now", Sql.Time(now)).With("@limit", (long)Math.Clamp(limit, 1, 10_000))), + ct); + + public Task> ListPendingAsync(int limit, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll(c.Command($"SELECT {Columns} FROM task WHERE state = 'Pending' ORDER BY due_at, priority DESC, id LIMIT @limit") + .With("@limit", (long)Math.Clamp(limit, 1, 10_000))), + ct); + + public Task TryStartAsync(long taskId, DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command("UPDATE task SET state = 'Running', started_at = @at WHERE id = @id AND state = 'Pending'") + .With("@at", Sql.Time(at)).With("@id", taskId).ExecuteNonQuery() == 1, + ct); + + public Task CompleteAsync(long taskId, DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => Require(w.Command("UPDATE task SET state = 'Done', completed_at = @at, last_error = NULL WHERE id = @id") + .With("@at", Sql.Time(at)).With("@id", taskId).ExecuteNonQuery(), taskId), + ct); + + public Task FailAsync(long taskId, DateTimeOffset at, string error, DateTimeOffset? retryAt, CancellationToken ct = default) => + db.WriteAsync( + w => Require(w.Command(""" + UPDATE task SET attempts = attempts + 1, last_error = @e, + state = CASE WHEN @retry IS NULL THEN 'Failed' ELSE 'Pending' END, + due_at = COALESCE(@retry, due_at), + completed_at = CASE WHEN @retry IS NULL THEN @at ELSE NULL END, + started_at = CASE WHEN @retry IS NULL THEN started_at ELSE NULL END + WHERE id = @id + """).With("@e", error).With("@retry", Sql.Time(retryAt)).With("@at", Sql.Time(at)).With("@id", taskId).ExecuteNonQuery(), taskId), + ct); + + public Task RescheduleAsync(long taskId, DateTimeOffset dueAt, CancellationToken ct = default) => + db.WriteAsync( + w => Require(w.Command("UPDATE task SET due_at = @d WHERE id = @id").With("@d", Sql.Time(dueAt)).With("@id", taskId).ExecuteNonQuery(), taskId), + ct); + + public Task CancelAsync(long taskId, DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command("UPDATE task SET state = 'Cancelled', completed_at = @at WHERE id = @id AND state IN ('Pending', 'Running')") + .With("@at", Sql.Time(at)).With("@id", taskId).ExecuteNonQuery(), + ct); + + public Task CancelForAccountAsync(long accountId, DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command("UPDATE task SET state = 'Cancelled', completed_at = @at WHERE account_id = @a AND state = 'Pending'") + .With("@at", Sql.Time(at)).With("@a", accountId).ExecuteNonQuery(), + ct); + + public Task RequeueRunningAsync(CancellationToken ct = default) => + db.WriteAsync(w => w.Command("UPDATE task SET state = 'Pending', started_at = NULL WHERE state = 'Running'").ExecuteNonQuery(), ct); + + public Task PurgeFinishedAsync(DateTimeOffset before, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command("DELETE FROM task WHERE state IN ('Done', 'Failed', 'Cancelled') AND completed_at < @b") + .With("@b", Sql.Time(before)).ExecuteNonQuery(), + ct); + + private static void Require(int rows, long taskId) + { + if (rows == 0) + { + throw new KeyNotFoundException($"Attività {taskId} non trovata."); + } + } +} + +internal sealed class ActionLogStore(FebeDatabase db) : IActionLogStore +{ + private static readonly TimeSpan Window = TimeSpan.FromMinutes(60); + + public Task AppendAsync(ActionLogRecord record, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(record); + ArgumentOutOfRangeException.ThrowIfNegative(record.Amount); + return db.WriteAsync( + w => + { + w.Command("INSERT INTO action_log (at, category, account_id, session_id, amount) VALUES (@at, @c, @a, @s, @n)") + .With("@at", Sql.Time(record.At)).With("@c", Sql.Enum(record.Category)).With("@a", Sql.Int(record.AccountId)) + .With("@s", Sql.Int(record.SessionId)).With("@n", record.Amount) + .ExecuteNonQuery(); + return record with { Id = w.LastInsertRowId() }; + }, + ct); + } + + public Task SumAsync(ActionKind category, DateTimeOffset from, DateTimeOffset to, long? accountId = null, CancellationToken ct = default) => + db.ReadAsync( + c => c.Command(""" + SELECT COALESCE(SUM(amount), 0) FROM action_log + WHERE category = @c AND at >= @f AND at < @t AND (@a IS NULL OR account_id = @a) + """).With("@c", Sql.Enum(category)).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).With("@a", Sql.Int(accountId)) + .ScalarInt64(), + ct); + + public Task> GetUsageAsync(DateTimeOffset now, TimeZoneInfo zone, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(zone); + var (dayStart, dayEnd) = LocalCalendar.DayBounds(now, zone); + var hourStart = now - Window; + var from = hourStart < dayStart ? hourStart : dayStart; + return db.ReadAsync>( + c => + { + // Rolling window (now − 60 min, now]; the action at exactly now − 60 min has left the window. + using var r = c.Command(""" + SELECT category, + COALESCE(SUM(CASE WHEN at > @hs AND at <= @now THEN amount ELSE 0 END), 0), + COALESCE(SUM(CASE WHEN at >= @ds AND at < @de THEN amount ELSE 0 END), 0) + FROM action_log WHERE at >= @from AND at < @de + GROUP BY category + """) + .With("@hs", Sql.Time(hourStart)).With("@now", Sql.Time(now)).With("@ds", Sql.Time(dayStart)) + .With("@de", Sql.Time(dayEnd)).With("@from", Sql.Time(from)) + .ExecuteReader(); + var usage = Enum.GetValues().ToDictionary(k => k, _ => default(BudgetUsage)); + while (r.Read()) + { + if (Enum.TryParse(r.GetString(0), out var kind)) + { + usage[kind] = new BudgetUsage(r.GetInt64(1), r.GetInt64(2)); + } + } + + return usage; + }, + ct); + } + + public Task GetLastActionAtAsync(ActionKind? category = null, CancellationToken ct = default) => + db.ReadAsync( + c => + { + var command = category is { } k + ? c.Command("SELECT MAX(at) FROM action_log WHERE category = @c").With("@c", Sql.Enum(k)) + : c.Command("SELECT MAX(at) FROM action_log WHERE category <> @c").With("@c", Sql.Enum(ActionKind.DataDownload)); + var value = command.ExecuteScalar(); + return value is long ms ? Sql.ToTime(ms) : (DateTimeOffset?)null; + }, + ct); + + public Task> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var r = c.Command(""" + SELECT id, at, category, account_id, session_id, amount FROM action_log WHERE at >= @f AND at < @t ORDER BY at, id + """).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(new ActionLogRecord + { + Id = r.GetInt64(0), + At = r.GetTime(1), + Category = r.GetEnum(2), + AccountId = r.GetInt64OrNull(3), + SessionId = r.GetInt64OrNull(4), + Amount = r.GetInt64(5), + }); + } + + return list; + }, + ct); + + public Task PruneAsync(DateTimeOffset before, CancellationToken ct = default) => + db.WriteAsync(w => w.Command("DELETE FROM action_log WHERE at < @b").With("@b", Sql.Time(before)).ExecuteNonQuery(), ct); +} + +internal sealed class SessionStore(FebeDatabase db) : ISessionStore +{ + private const string Columns = "id, started_at, ended_at, action_count, outcome, summary"; + + private static SessionRecord Read(SqliteDataReader r) => new() + { + Id = r.GetInt64(0), + StartedAt = r.GetTime(1), + EndedAt = r.GetTimeOrNull(2), + ActionCount = r.GetInt32(3), + Outcome = r.GetEnum(4), + Summary = r.GetTextOrNull(5), + }; + + private static List ReadAll(SqliteCommand command) + { + using var r = command.ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(Read(r)); + } + + return list; + } + + public Task StartAsync(DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => + { + w.Command("INSERT INTO session (started_at, outcome) VALUES (@at, 'Running')").With("@at", Sql.Time(at)).ExecuteNonQuery(); + return new SessionRecord { Id = w.LastInsertRowId(), StartedAt = at, Outcome = SessionOutcome.Running }; + }, + ct); + + public Task EndAsync(long sessionId, DateTimeOffset at, SessionOutcome outcome, int actionCount, string? summary = null, CancellationToken ct = default) => + db.WriteAsync( + w => + { + if (w.Command("UPDATE session SET ended_at = @at, outcome = @o, action_count = @n, summary = @s WHERE id = @id") + .With("@at", Sql.Time(at)).With("@o", Sql.Enum(outcome)).With("@n", (long)actionCount).With("@s", Sql.Text(summary)) + .With("@id", sessionId).ExecuteNonQuery() == 0) + { + throw new KeyNotFoundException($"Sessione {sessionId} non trovata."); + } + }, + ct); + + public Task GetAsync(long sessionId, CancellationToken ct = default) => + db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM session WHERE id = @id").With("@id", sessionId)).FirstOrDefault(), ct); + + public Task GetLastAsync(CancellationToken ct = default) => + db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM session ORDER BY started_at DESC, id DESC LIMIT 1")).FirstOrDefault(), ct); + + public Task> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll(c.Command($""" + SELECT {Columns} FROM session WHERE started_at < @t AND (ended_at IS NULL OR ended_at > @f) ORDER BY started_at, id + """).With("@f", Sql.Time(from)).With("@t", Sql.Time(to))), + ct); + + public Task CloseInterruptedAsync(DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command(""" + UPDATE session SET ended_at = MAX(@at, started_at), outcome = 'Interrupted' + WHERE ended_at IS NULL + """).With("@at", Sql.Time(at)).ExecuteNonQuery(), + ct); +} + +internal sealed class IncidentStore(FebeDatabase db) : IIncidentStore +{ + private const string Columns = "id, at, level, signal, url, stopped_until, resolved_at, session_id, note"; + + private static Incident Read(SqliteDataReader r) => new() + { + Id = r.GetInt64(0), + At = r.GetTime(1), + Level = r.GetEnum(2), + Signal = r.GetString(3), + Url = r.GetTextOrNull(4), + StoppedUntil = r.GetTimeOrNull(5), + ResolvedAt = r.GetTimeOrNull(6), + SessionId = r.GetInt64OrNull(7), + Note = r.GetTextOrNull(8), + }; + + private static List ReadAll(SqliteCommand command) + { + using var r = command.ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(Read(r)); + } + + return list; + } + + public Task OpenAsync(Incident incident, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(incident); + ArgumentException.ThrowIfNullOrWhiteSpace(incident.Signal); + return db.WriteAsync( + w => + { + w.Command(""" + INSERT INTO incident (at, level, signal, url, stopped_until, resolved_at, session_id, note) + VALUES (@at, @l, @s, @u, @su, @r, @sid, @n) + """) + .With("@at", Sql.Time(incident.At)).With("@l", Sql.Enum(incident.Level)).With("@s", incident.Signal) + .With("@u", Sql.Text(incident.Url)).With("@su", Sql.Time(incident.StoppedUntil)).With("@r", Sql.Time(incident.ResolvedAt)) + .With("@sid", Sql.Int(incident.SessionId)).With("@n", Sql.Text(incident.Note)) + .ExecuteNonQuery(); + return incident with { Id = w.LastInsertRowId() }; + }, + ct); + } + + public Task ResolveAsync(long incidentId, DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => + { + if (w.Command("UPDATE incident SET resolved_at = COALESCE(resolved_at, @at) WHERE id = @id") + .With("@at", Sql.Time(at)).With("@id", incidentId).ExecuteNonQuery() == 0) + { + throw new KeyNotFoundException($"Arresto {incidentId} non trovato."); + } + }, + ct); + + public Task GetAsync(long incidentId, CancellationToken ct = default) => + db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM incident WHERE id = @id").With("@id", incidentId)).FirstOrDefault(), ct); + + public Task> ListOpenAsync(CancellationToken ct = default) => + db.ReadAsync>(c => ReadAll(c.Command($"SELECT {Columns} FROM incident WHERE resolved_at IS NULL ORDER BY at, id")), ct); + + public Task> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll(c.Command($"SELECT {Columns} FROM incident WHERE at >= @f AND at < @t ORDER BY at, id") + .With("@f", Sql.Time(from)).With("@t", Sql.Time(to))), + ct); + + public Task CountAsync(SignalLevel level, DateTimeOffset since, CancellationToken ct = default) => + db.ReadAsync( + c => (int)c.Command("SELECT COUNT(*) FROM incident WHERE level = @l AND at >= @s") + .With("@l", Sql.Enum(level)).With("@s", Sql.Time(since)).ScalarInt64(), + ct); +} + +internal sealed class EventStore(FebeDatabase db) : IEventStore +{ + private const string Columns = "id, at, severity, code, message, account_id, session_id"; + + private static EventRecord Read(SqliteDataReader r) => new() + { + Id = r.GetInt64(0), + At = r.GetTime(1), + Severity = r.GetEnum(2), + Code = r.GetString(3), + Message = r.GetString(4), + AccountId = r.GetInt64OrNull(5), + SessionId = r.GetInt64OrNull(6), + }; + + private static List ReadAll(SqliteCommand command) + { + using var r = command.ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(Read(r)); + } + + return list; + } + + public Task AppendAsync(EventRecord record, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(record); + ArgumentException.ThrowIfNullOrWhiteSpace(record.Code); + ArgumentNullException.ThrowIfNull(record.Message); + return db.WriteAsync( + w => + { + w.Command("INSERT INTO event (at, severity, code, message, account_id, session_id) VALUES (@at, @sv, @c, @m, @a, @s)") + .With("@at", Sql.Time(record.At)).With("@sv", Sql.Enum(record.Severity)).With("@c", record.Code) + .With("@m", record.Message).With("@a", Sql.Int(record.AccountId)).With("@s", Sql.Int(record.SessionId)) + .ExecuteNonQuery(); + return record with { Id = w.LastInsertRowId() }; + }, + ct); + } + + public Task> ListAsync(EventQuery query, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(query); + var severities = Enum.GetValues().Where(s => query.MinSeverity is null || s >= query.MinSeverity).Select(s => s.ToString()); + return db.ReadAsync>( + c => + { + var command = c.Command(string.Empty); + var list = command.AddList("sv", severities); + command.CommandText = $""" + SELECT {Columns} FROM event + WHERE (@before IS NULL OR id < @before) AND (@a IS NULL OR account_id = @a) AND severity IN ({list}) + AND (@f IS NULL OR at >= @f) AND (@t IS NULL OR at < @t) + ORDER BY id DESC LIMIT @limit + """; + command.With("@before", Sql.Int(query.BeforeId)).With("@a", Sql.Int(query.AccountId)) + .With("@f", Sql.Time(query.From)).With("@t", Sql.Time(query.To)) + .With("@limit", (long)Math.Clamp(query.Limit, 1, 1000)); + return ReadAll(command); + }, + ct); + } + + public Task> ListAfterAsync(long afterId, int limit = 200, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll(c.Command($"SELECT {Columns} FROM event WHERE id > @after ORDER BY id LIMIT @limit") + .With("@after", afterId).With("@limit", (long)Math.Clamp(limit, 1, 1000))), + ct); + + public Task PruneAsync(DateTimeOffset before, CancellationToken ct = default) => + db.WriteAsync(w => w.Command("DELETE FROM event WHERE at < @b").With("@b", Sql.Time(before)).ExecuteNonQuery(), ct); +} + +internal sealed class FollowingStore(FebeDatabase db) : IFollowingStore +{ + public Task UpsertAsync(IReadOnlyList records, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(records); + return db.WriteAsync( + w => + { + foreach (var record in records) + { + ArgumentException.ThrowIfNullOrWhiteSpace(record.Username); + var instagramId = EntryMapping.NormalizeId(record.InstagramId); + var username = record.Username.Trim().TrimStart('@'); + object? id = null; + if (instagramId is not null) + { + id = w.Command("SELECT id FROM \"following\" WHERE instagram_id = @i").With("@i", instagramId).ExecuteScalar(); + } + + id ??= w.Command("SELECT id FROM \"following\" WHERE username = @u AND (instagram_id IS NULL OR @i IS NULL) ORDER BY id LIMIT 1") + .With("@u", username).With("@i", Sql.Text(instagramId)).ExecuteScalar(); + + if (id is long existing) + { + w.Command(""" + UPDATE "following" SET instagram_id = COALESCE(@i, instagram_id), username = @u, display_name = @d, + is_private = @p, position = @pos, read_at = @r + WHERE id = @id + """) + .With("@i", Sql.Text(instagramId)).With("@u", username).With("@d", Sql.Text(record.DisplayName)) + .With("@p", Sql.Bool(record.IsPrivate)).With("@pos", (long)record.Position).With("@r", Sql.Time(record.ReadAt)) + .With("@id", existing).ExecuteNonQuery(); + } + else + { + w.Command(""" + INSERT INTO "following" (instagram_id, username, display_name, is_private, position, read_at) + VALUES (@i, @u, @d, @p, @pos, @r) + """) + .With("@i", Sql.Text(instagramId)).With("@u", username).With("@d", Sql.Text(record.DisplayName)) + .With("@p", Sql.Bool(record.IsPrivate)).With("@pos", (long)record.Position).With("@r", Sql.Time(record.ReadAt)) + .ExecuteNonQuery(); + } + } + }, + ct); + } + + public Task> ListAsync(CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var r = c.Command(""" + SELECT instagram_id, username, display_name, is_private, position, read_at FROM "following" ORDER BY position, id + """).ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(new FollowingRecord + { + InstagramId = r.GetTextOrNull(0), + Username = r.GetString(1), + DisplayName = r.GetTextOrNull(2), + IsPrivate = r.GetBoolOrNull(3), + Position = r.GetInt32(4), + ReadAt = r.GetTime(5), + }); + } + + return list; + }, + ct); + + public Task CountAsync(CancellationToken ct = default) => + db.ReadAsync(c => (int)c.Command("SELECT COUNT(*) FROM \"following\"").ScalarInt64(), ct); + + public Task GetLastReadAtAsync(CancellationToken ct = default) => + db.ReadAsync( + c => c.Command("SELECT MAX(read_at) FROM \"following\"").ExecuteScalar() is long ms ? Sql.ToTime(ms) : (DateTimeOffset?)null, + ct); + + public Task RemoveNotReadSinceAsync(DateTimeOffset readStartedAt, CancellationToken ct = default) => + db.WriteAsync(w => w.Command("DELETE FROM \"following\" WHERE read_at < @s").With("@s", Sql.Time(readStartedAt)).ExecuteNonQuery(), ct); + + public Task ClearAsync(CancellationToken ct = default) => + db.WriteAsync(w => w.Command("DELETE FROM \"following\"").ExecuteNonQuery(), ct); +} + +internal sealed class SettingsStore(FebeDatabase db) : ISettingsStore +{ + public Task GetAsync(string key, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(key); + return db.ReadAsync(c => c.Command("SELECT value FROM setting WHERE key = @k").With("@k", key).ExecuteScalar() as string, ct); + } + + public Task SetAsync(string key, string? value, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(key); + return db.WriteAsync(w => Set(w, key, value), ct); + } + + public Task SetManyAsync(IReadOnlyDictionary values, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(values); + foreach (var key in values.Keys) + { + ArgumentException.ThrowIfNullOrWhiteSpace(key); + } + + return db.WriteAsync( + w => + { + foreach (var (key, value) in values) + { + Set(w, key, value); + } + }, + ct); + } + + public Task> GetAllAsync(CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var r = c.Command("SELECT key, value FROM setting ORDER BY key").ExecuteReader(); + var values = new Dictionary(StringComparer.Ordinal); + while (r.Read()) + { + values[r.GetString(0)] = r.GetString(1); + } + + return values; + }, + ct); + + private static void Set(WriteContext w, string key, string? value) + { + if (value is null) + { + w.Command("DELETE FROM setting WHERE key = @k").With("@k", key).ExecuteNonQuery(); + } + else + { + w.Command("INSERT INTO setting (key, value) VALUES (@k, @v) ON CONFLICT (key) DO UPDATE SET value = excluded.value") + .With("@k", key).With("@v", value).ExecuteNonQuery(); + } + } +} diff --git a/src/Febe.Data/Stores/EntryMapping.cs b/src/Febe.Data/Stores/EntryMapping.cs new file mode 100644 index 0000000..7c3d245 --- /dev/null +++ b/src/Febe.Data/Stores/EntryMapping.cs @@ -0,0 +1,191 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Microsoft.Data.Sqlite; + +namespace Febe.Data.Stores; + +/// Column lists and readers shared by the entry, media and highlight stores. +internal static class EntryMapping +{ + public const string EntryColumns = + "e.id, e.account_id, e.kind, e.instagram_id, e.code, e.published_at, e.caption, e.author_username, e.author_instagram_id, " + + "e.state, e.provenance, e.discovered_at, e.downloaded_at, e.deleted_at, e.expires_at"; + + public const int EntryColumnCount = 15; + + public const string MediaColumns = + "m.id, m.entry_id, m.position, m.kind, m.instagram_id, m.width, m.height, m.duration_ms, m.state, m.relative_path, m.bytes, " + + "m.sha256, m.phash, m.has_thumbnail, m.source_url, m.cover_url, m.source_seen_at, m.attempts, m.last_error, m.downloaded_at"; + + public const int MediaColumnCount = 20; + + /// + /// Tile columns; the query must join media c (the cover, see ). The user name is a + /// correlated subquery on purpose: with a join, SQLite (with ANALYZE statistics) drives the query from the small + /// account table and sorts every entry, which costs a second on 200,000 entries instead of a millisecond. + /// + public const string TileColumns = + "e.id, e.account_id, (SELECT a.username FROM account a WHERE a.id = e.account_id), e.kind, e.published_at, e.state, e.provenance, " + + "(SELECT COUNT(*) FROM media mc WHERE mc.entry_id = e.id), " + + "c.id, c.kind, c.width, c.height, c.duration_ms, c.sha256, c.has_thumbnail"; + + /// The cover is the first file present, or the first file. + public const string TileFrom = + "FROM entry e " + + "LEFT JOIN media c ON c.id = (SELECT m1.id FROM media m1 WHERE m1.entry_id = e.id " + + "ORDER BY (m1.state IN ('Downloaded', 'Imported')) DESC, m1.position LIMIT 1)"; + + public static readonly string VisibleStates = string.Join(", ", EntryStateRules.Visible.Select(s => $"'{s}'")); + + public static Entry ReadEntry(SqliteDataReader r, int o = 0) => new() + { + Id = r.GetInt64(o), + AccountId = r.GetInt64(o + 1), + Kind = r.GetEnum(o + 2), + InstagramId = r.GetTextOrNull(o + 3), + Code = r.GetTextOrNull(o + 4), + PublishedAt = r.GetTime(o + 5), + Caption = r.GetTextOrNull(o + 6), + AuthorUsername = r.GetTextOrNull(o + 7), + AuthorInstagramId = r.GetTextOrNull(o + 8), + State = r.GetEnum(o + 9), + Provenance = r.GetEnum(o + 10), + DiscoveredAt = r.GetTime(o + 11), + DownloadedAt = r.GetTimeOrNull(o + 12), + DeletedAt = r.GetTimeOrNull(o + 13), + ExpiresAt = r.GetTimeOrNull(o + 14), + }; + + public static Media ReadMedia(SqliteDataReader r, int o = 0) => new() + { + Id = r.GetInt64(o), + EntryId = r.GetInt64(o + 1), + Position = r.GetInt32(o + 2), + Kind = r.GetEnum(o + 3), + InstagramId = r.GetTextOrNull(o + 4), + Width = r.GetInt32OrNull(o + 5), + Height = r.GetInt32OrNull(o + 6), + Duration = r.GetDurationOrNull(o + 7), + State = r.GetEnum(o + 8), + RelativePath = r.GetTextOrNull(o + 9), + Bytes = r.GetInt64OrNull(o + 10), + Sha256 = r.GetTextOrNull(o + 11), + PerceptualHash = r.GetHashOrNull(o + 12), + HasThumbnail = r.GetBool(o + 13), + SourceUrl = r.GetTextOrNull(o + 14), + CoverUrl = r.GetTextOrNull(o + 15), + SourceSeenAt = r.GetTimeOrNull(o + 16), + Attempts = r.GetInt32(o + 17), + LastError = r.GetTextOrNull(o + 18), + DownloadedAt = r.GetTimeOrNull(o + 19), + }; + + public static Core.Storage.LibraryTile ReadTile(SqliteDataReader r) => new( + EntryId: r.GetInt64(0), + AccountId: r.GetInt64(1), + Username: r.GetString(2), + Kind: r.GetEnum(3), + PublishedAt: r.GetTime(4), + State: r.GetEnum(5), + Provenance: r.GetEnum(6), + MediaCount: r.GetInt32(7), + CoverMediaId: r.GetInt64OrNull(8), + CoverKind: r.GetEnumOrNull(9), + CoverWidth: r.GetInt32OrNull(10), + CoverHeight: r.GetInt32OrNull(11), + CoverDuration: r.GetDurationOrNull(12), + CoverSha256: r.GetTextOrNull(13), + CoverHasThumbnail: !r.IsDBNull(14) && r.GetBool(14)); + + public static void BindEntry(SqliteCommand c, Entry e) => + c.With("@account_id", e.AccountId) + .With("@kind", Sql.Enum(e.Kind)) + .With("@instagram_id", Sql.Text(NormalizeId(e.InstagramId))) + .With("@code", Sql.Text(e.Code)) + .With("@published_at", Sql.Time(e.PublishedAt)) + .With("@caption", Sql.Text(e.Caption)) + .With("@author_username", Sql.Text(e.AuthorUsername)) + .With("@author_instagram_id", Sql.Text(e.AuthorInstagramId)) + .With("@state", Sql.Enum(e.State)) + .With("@provenance", Sql.Enum(e.Provenance)) + .With("@discovered_at", Sql.Time(e.DiscoveredAt)) + .With("@downloaded_at", Sql.Time(e.DownloadedAt)) + .With("@deleted_at", Sql.Time(e.DeletedAt)) + .With("@expires_at", Sql.Time(e.ExpiresAt)) + .With("@search_text", TextSearch.ForEntry(e.Caption, e.AuthorUsername)); + + public static void BindMedia(SqliteCommand c, Media m) => + c.With("@entry_id", m.EntryId) + .With("@position", (long)m.Position) + .With("@kind", Sql.Enum(m.Kind)) + .With("@instagram_id", Sql.Text(NormalizeId(m.InstagramId))) + .With("@width", Sql.Int(m.Width)) + .With("@height", Sql.Int(m.Height)) + .With("@duration_ms", Sql.Duration(m.Duration)) + .With("@state", Sql.Enum(m.State)) + .With("@relative_path", Sql.Text(m.RelativePath)) + .With("@bytes", Sql.Int(m.Bytes)) + .With("@sha256", Sql.Text(m.Sha256?.ToLowerInvariant())) + .With("@phash", Sql.Hash(m.PerceptualHash)) + .With("@has_thumbnail", Sql.Bool(m.HasThumbnail)) + .With("@source_url", Sql.Text(m.SourceUrl)) + .With("@cover_url", Sql.Text(m.CoverUrl)) + .With("@source_seen_at", Sql.Time(m.SourceSeenAt)) + .With("@attempts", (long)m.Attempts) + .With("@last_error", Sql.Text(m.LastError)) + .With("@downloaded_at", Sql.Time(m.DownloadedAt)); + + public const string InsertMediaSql = """ + INSERT INTO media (entry_id, position, kind, instagram_id, width, height, duration_ms, state, relative_path, bytes, sha256, phash, + has_thumbnail, source_url, cover_url, source_seen_at, attempts, last_error, downloaded_at) + VALUES (@entry_id, @position, @kind, @instagram_id, @width, @height, @duration_ms, @state, @relative_path, @bytes, @sha256, @phash, + @has_thumbnail, @source_url, @cover_url, @source_seen_at, @attempts, @last_error, @downloaded_at) + """; + + public static string? NormalizeId(string? id) => string.IsNullOrWhiteSpace(id) ? null : id.Trim(); + + /// Files of an entry; creates (or reuses) a command for a SQL text. + public static List ReadMediaOf(Func command, long entryId) + { + using var r = command($"SELECT {MediaColumns} FROM media m WHERE m.entry_id = @e ORDER BY m.position") + .With("@e", entryId).ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(ReadMedia(r)); + } + + return list; + } + + public static Entry? ReadEntryById(Func command, long entryId) + { + using var r = command($"SELECT {EntryColumns} FROM entry e WHERE e.id = @id").With("@id", entryId).ExecuteReader(); + return r.Read() ? ReadEntry(r) : null; + } + + /// Recomputes and stores the state of an entry from its files. Returns the new state. + public static EntryState RecomputeState(WriteContext w, long entryId, DateTimeOffset? downloadedAt = null) + { + var entry = ReadEntryById(w.Command, entryId) + ?? throw new KeyNotFoundException($"Elemento {entryId} non trovato."); + var states = new List(); + using (var r = w.Command("SELECT state FROM media WHERE entry_id = @e").With("@e", entryId).ExecuteReader()) + { + while (r.Read()) + { + states.Add(r.GetEnum(0)); + } + } + + var state = EntryStateRules.FromMedia(entry.State, entry.Provenance, states); + var becameComplete = state is EntryState.Downloaded or EntryState.Imported && entry.DownloadedAt is null; + w.Command("UPDATE entry SET state = @s, downloaded_at = CASE WHEN @c = 1 THEN @d ELSE downloaded_at END WHERE id = @id") + .With("@s", Sql.Enum(state)) + .With("@c", becameComplete && downloadedAt is not null ? 1L : 0L) + .With("@d", Sql.Time(downloadedAt)) + .With("@id", entryId) + .ExecuteNonQuery(); + return state; + } +} diff --git a/src/Febe.Data/Stores/EntryStore.cs b/src/Febe.Data/Stores/EntryStore.cs new file mode 100644 index 0000000..0e831c6 --- /dev/null +++ b/src/Febe.Data/Stores/EntryStore.cs @@ -0,0 +1,521 @@ +using System.Text; +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; +using Microsoft.Data.Sqlite; +using static Febe.Data.Stores.EntryMapping; + +namespace Febe.Data.Stores; + +internal sealed class EntryStore(FebeDatabase db) : IEntryStore +{ + public Task GetAsync(long entryId, CancellationToken ct = default) => + db.ReadAsync(c => ReadEntryById(sql => c.Command(sql), entryId), ct); + + public Task GetWithMediaAsync(long entryId, CancellationToken ct = default) => + db.ReadAsync( + c => + { + var entry = ReadEntryById(sql => c.Command(sql), entryId); + return entry is null ? null : new EntryWithMedia(entry, ReadMediaOf(sql => c.Command(sql), entryId)); + }, + ct); + + public Task FindAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(instagramId); + return db.ReadAsync(c => FindIdentity(sql => c.Command(sql), accountId, kind, instagramId.Trim()), ct); + } + + public async Task IsKnownAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default) => + await FindAsync(accountId, kind, instagramId, ct).ConfigureAwait(false) is not null; + + public Task> GetKnownInstagramIdsAsync(long accountId, EntryKind kind, IReadOnlyCollection instagramIds, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(instagramIds); + var ids = instagramIds.Where(i => !string.IsNullOrWhiteSpace(i)).Select(i => i.Trim()).Distinct(StringComparer.Ordinal).ToList(); + return db.ReadAsync>( + c => + { + var known = new HashSet(StringComparer.Ordinal); + foreach (var chunk in ids.Chunk(500)) + { + var command = c.Command(string.Empty).With("@a", accountId).With("@k", Sql.Enum(kind)); + var list = command.AddList("i", chunk); + command.CommandText = $"SELECT instagram_id FROM entry WHERE account_id = @a AND kind = @k AND instagram_id IN ({list})"; + using var r = command.ExecuteReader(); + while (r.Read()) + { + known.Add(r.GetString(0)); + } + } + + return known; + }, + ct); + } + + public Task> FindByInstagramIdAsync(long accountId, string instagramId, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(instagramId); + return db.ReadAsync>( + c => ReadEntries(c.Command($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a AND e.instagram_id = @i ORDER BY e.id") + .With("@a", accountId).With("@i", instagramId.Trim())), + ct); + } + + public Task FindByPublicationTimeAsync(long accountId, EntryKind kind, DateTimeOffset publishedAt, TimeSpan tolerance, CancellationToken ct = default) + { + var ms = Sql.Time(publishedAt); + var tol = (long)Math.Abs(tolerance.TotalMilliseconds); + return db.ReadAsync( + c => + { + using var r = c.Command($""" + SELECT {EntryColumns} FROM entry e + WHERE e.account_id = @a AND e.kind = @k AND e.published_at BETWEEN @from AND @to + ORDER BY abs(e.published_at - @p), e.id LIMIT 1 + """) + .With("@a", accountId).With("@k", Sql.Enum(kind)).With("@from", ms - tol).With("@to", ms + tol).With("@p", ms) + .ExecuteReader(); + return r.Read() ? ReadEntry(r) : null; + }, + ct); + } + + public Task AddAsync(Entry entry, IReadOnlyList media, CancellationToken ct = default) + { + Validate(entry, media); + return db.WriteAsync(w => Add(w, entry, media), ct); + } + + public Task> AddManyAsync(IReadOnlyList entries, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(entries); + foreach (var item in entries) + { + Validate(item.Entry, item.Media); + } + + return db.WriteAsync>(w => entries.Select(item => Add(w, item.Entry, item.Media)).ToList(), ct); + } + + public Task UpdateAsync(Entry entry, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(entry); + return db.WriteAsync( + w => + { + var c = w.Command(""" + UPDATE entry SET instagram_id = @instagram_id, code = @code, published_at = @published_at, caption = @caption, + author_username = @author_username, author_instagram_id = @author_instagram_id, state = @state, + provenance = @provenance, discovered_at = @discovered_at, downloaded_at = @downloaded_at, + deleted_at = @deleted_at, expires_at = @expires_at, search_text = @search_text + WHERE id = @id + """); + BindEntry(c, entry); + c.With("@id", entry.Id); + try + { + if (c.ExecuteNonQuery() == 0) + { + throw new KeyNotFoundException($"Elemento {entry.Id} non trovato."); + } + } + catch (SqliteException ex) when (ex.IsUniqueViolation()) + { + throw new DuplicateRecordException("Esiste già un elemento con lo stesso identificativo Instagram per questo account e tipo.", ex); + } + }, + ct); + } + + public Task SetStateAsync(long entryId, EntryState state, CancellationToken ct = default) => + db.WriteAsync( + w => + { + if (w.Command("UPDATE entry SET state = @s WHERE id = @id").With("@s", Sql.Enum(state)).With("@id", entryId).ExecuteNonQuery() == 0) + { + throw new KeyNotFoundException($"Elemento {entryId} non trovato."); + } + }, + ct); + + public Task RecomputeStateAsync(long entryId, CancellationToken ct = default) => + db.WriteAsync(w => RecomputeState(w, entryId), ct); + + public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => + { + var rows = w.Command("UPDATE entry SET state = 'Deleted', deleted_at = @at WHERE id = @id") + .With("@at", Sql.Time(at)).With("@id", entryId).ExecuteNonQuery(); + if (rows == 0) + { + throw new KeyNotFoundException($"Elemento {entryId} non trovato."); + } + + w.Command(""" + UPDATE media SET state = 'Deleted', relative_path = NULL, has_thumbnail = 0, phash = NULL, source_url = NULL, cover_url = NULL + WHERE entry_id = @id + """).With("@id", entryId).ExecuteNonQuery(); + }, + ct); + + public Task RemoveAsync(long entryId, CancellationToken ct = default) => + db.WriteAsync(w => w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(), ct); + + public Task> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default) + { + options ??= new EntryListOptions(); + return db.ReadAsync>( + c => + { + var command = c.Command(string.Empty).With("@a", accountId).With("@limit", (long)Math.Clamp(options.Limit, 1, 10_000)); + var sql = new StringBuilder($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a"); + if (options.Kind is { } kind) + { + sql.Append(" AND e.kind = @k"); + command.With("@k", Sql.Enum(kind)); + } + + if (options.States is { Count: > 0 } states) + { + sql.Append(" AND e.state IN (").Append(command.AddList("s", states.Select(s => s.ToString()))).Append(')'); + } + + if (options.Before is { } before) + { + sql.Append(" AND (e.published_at, e.id) < (@bp, @bi)"); + command.With("@bp", Sql.Time(before.PublishedAt)).With("@bi", before.EntryId); + } + + sql.Append(" ORDER BY e.published_at DESC, e.id DESC LIMIT @limit"); + command.CommandText = sql.ToString(); + return ReadEntries(command); + }, + ct); + } + + public Task CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) => + db.ReadAsync( + c => (int)c.Command(""" + SELECT COUNT(*) FROM entry WHERE account_id = @a AND kind = @k AND discovered_at >= @f AND discovered_at < @t + """).With("@a", accountId).With("@k", Sql.Enum(kind)).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).ScalarInt64(), + ct); + + public Task QueryLibraryAsync(LibraryQuery query, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(query); + var limit = Math.Clamp(query.Limit, 1, 1000); + return db.ReadAsync( + c => + { + // Phase 1: keys only, so that sorting never computes the tile columns of rows outside the window. + var command = c.Command(string.Empty); + var where = BuildWhere(c, command, query.Filter); + var newer = query.Direction == LibraryDirection.Newer; + var sql = new StringBuilder($"SELECT e.id FROM entry e WHERE {where}"); + if (query.Cursor is { } cursor) + { + sql.Append(newer ? " AND (e.published_at, e.id) > (@cp, @ci)" : " AND (e.published_at, e.id) < (@cp, @ci)"); + command.With("@cp", Sql.Time(cursor.PublishedAt)).With("@ci", cursor.EntryId); + } + + // With a text search the whole table is scanned and the matches sorted: about a tenth of a second on + // 200,000 entries whether the word is rare or common, instead of walking the index row by row. + var order = string.IsNullOrWhiteSpace(query.Filter.Search) ? "e.published_at" : "+e.published_at"; + sql.Append(newer ? $" ORDER BY {order} ASC, e.id ASC" : $" ORDER BY {order} DESC, e.id DESC"); + sql.Append(" LIMIT @limit"); + command.With("@limit", (long)limit + 1); + command.CommandText = sql.ToString(); + + var ids = new List(limit + 1); + using (var r = command.ExecuteReader()) + { + while (r.Read()) + { + ids.Add(r.GetInt64(0)); + } + } + + var moreInDirection = ids.Count > limit; + if (moreInDirection) + { + ids.RemoveAt(ids.Count - 1); + } + + if (newer) + { + ids.Reverse(); + } + + // Phase 2: the tiles of the window, in display order. + var tiles = TilesOf(c, ids); + + if (tiles.Count == 0) + { + return new LibraryPage(tiles, null, null); + } + + var first = new LibraryCursor(tiles[0].PublishedAt, tiles[0].EntryId); + var last = new LibraryCursor(tiles[^1].PublishedAt, tiles[^1].EntryId); + bool hasOlder, hasNewer; + if (newer) + { + hasNewer = moreInDirection; + hasOlder = Exists(c, query.Filter, last, older: true); + } + else + { + hasOlder = moreInDirection; + hasNewer = query.Cursor is not null && Exists(c, query.Filter, first, older: false); + } + + return new LibraryPage(tiles, hasOlder ? last : null, hasNewer ? first : null); + }, + ct); + } + + public Task GetLibraryTotalsAsync(LibraryFilter filter, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(filter); + return db.ReadAsync( + c => + { + var command = c.Command(string.Empty); + var where = BuildWhere(c, command, filter); + command.CommandText = $"SELECT COUNT(*), COUNT(DISTINCT e.account_id) FROM entry e WHERE {where}"; + using var r = command.ExecuteReader(); + r.Read(); + return new LibraryTotals(r.GetInt32(0), r.GetInt32(1)); + }, + ct); + } + + public Task> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(filter); + ArgumentNullException.ThrowIfNull(zone); + return db.ReadAsync>( + c => + { + // Stream the publication times in index order and fold them into local days here: no time zone logic + // in SQL, no sort, and the day bounds are computed once per day rather than once per entry. + var command = c.Command(string.Empty); + var where = BuildWhere(c, command, filter); + command.CommandText = $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at"; + var days = new List(); + long dayStart = long.MaxValue, dayEnd = long.MinValue; + DateOnly day = default; + var count = 0; + using (var r = command.ExecuteReader()) + { + while (r.Read()) + { + var ms = r.GetInt64(0); + if (ms < dayStart || ms >= dayEnd) + { + if (count > 0) + { + days.Add(new DayCount(day, count)); + } + + day = LocalCalendar.Today(Sql.ToTime(ms), zone); + var (start, end) = LocalCalendar.DayBounds(day, zone); + (dayStart, dayEnd, count) = (Sql.Time(start), Sql.Time(end), 0); + } + + count++; + } + } + + if (count > 0) + { + days.Add(new DayCount(day, count)); + } + + days.Reverse(); + return days; + }, + ct); + } + + public Task> GetTilesAsync(IReadOnlyList entryIds, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(entryIds); + return db.ReadAsync>(c => TilesOf(c, entryIds), ct); + } + + // --------------------------------------------------------------------------------------------- + + /// Tiles of the given entries, in the given order (unknown keys are skipped). + private static List TilesOf(SqliteConnection c, IReadOnlyList entryIds) + { + var byId = new Dictionary(entryIds.Count); + foreach (var chunk in entryIds.Distinct().Chunk(500)) + { + using var command = c.Command(string.Empty); + var list = command.AddList("i", chunk); + command.CommandText = $"SELECT {TileColumns} {TileFrom} WHERE e.id IN ({list})"; + using var r = command.ExecuteReader(); + while (r.Read()) + { + var tile = ReadTile(r); + byId[tile.EntryId] = tile; + } + } + + return entryIds.Where(byId.ContainsKey).Select(id => byId[id]).ToList(); + } + + private static void Validate(Entry entry, IReadOnlyList media) + { + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(media); + if (media.Select(m => m.Position).Distinct().Count() != media.Count) + { + throw new ArgumentException("Le posizioni dei file di un elemento devono essere distinte.", nameof(media)); + } + + if (media.Any(m => m.Position < 1)) + { + throw new ArgumentException("Le posizioni dei file partono da 1.", nameof(media)); + } + } + + private static AddEntryResult Add(WriteContext w, Entry entry, IReadOnlyList media) + { + var instagramId = NormalizeId(entry.InstagramId); + if (instagramId is not null && FindIdentity(w.Command, entry.AccountId, entry.Kind, instagramId) is { } existing) + { + return new AddEntryResult(new EntryWithMedia(existing, ReadMediaOf(w.Command, existing.Id)), false); + } + + var state = EntryStateRules.FromMedia(entry.State, entry.Provenance, media.Select(m => m.State).ToList()); + var stored = entry with { InstagramId = instagramId, State = state }; + var insert = w.Command(""" + INSERT INTO entry (account_id, kind, instagram_id, code, published_at, caption, author_username, author_instagram_id, state, + provenance, discovered_at, downloaded_at, deleted_at, expires_at, search_text) + VALUES (@account_id, @kind, @instagram_id, @code, @published_at, @caption, @author_username, @author_instagram_id, @state, + @provenance, @discovered_at, @downloaded_at, @deleted_at, @expires_at, @search_text) + """); + BindEntry(insert, stored); + insert.ExecuteNonQuery(); + var entryId = w.LastInsertRowId(); + stored = stored with { Id = entryId }; + + var files = new List(media.Count); + foreach (var file in media.OrderBy(m => m.Position)) + { + var row = file with { EntryId = entryId, Sha256 = file.Sha256?.ToLowerInvariant(), InstagramId = NormalizeId(file.InstagramId) }; + var command = w.Command(InsertMediaSql); + BindMedia(command, row); + command.ExecuteNonQuery(); + files.Add(row with { Id = w.LastInsertRowId() }); + } + + return new AddEntryResult(new EntryWithMedia(stored, files), true); + } + + private static Entry? FindIdentity(Func command, long accountId, EntryKind kind, string instagramId) + { + using var r = command($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a AND e.kind = @k AND e.instagram_id = @i") + .With("@a", accountId).With("@k", Sql.Enum(kind)).With("@i", instagramId).ExecuteReader(); + return r.Read() ? ReadEntry(r) : null; + } + + private static List ReadEntries(SqliteCommand command) + { + using var r = command.ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(ReadEntry(r)); + } + + return list; + } + + private static bool Exists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older) + { + var command = c.Command(string.Empty); + var where = BuildWhere(c, command, filter); + command.CommandText = $"SELECT EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi))"; + command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId); + return command.ScalarInt64() != 0; + } + + /// The WHERE clause of a library filter on entry e; parameters are added to . + internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter) + { + var parts = new List(); + var states = filter.States is { Count: > 0 } s ? s : EntryStateRules.Visible; + // The unary + keeps SQLite from using the state and kind indexes for these broad terms: the keyset scan of the + // publication index is what keeps a window fast over 200,000 entries, with or without ANALYZE statistics. + parts.Add($"+e.state IN ({command.AddList("st", states.Select(x => x.ToString()))})"); + + parts.Add(filter.Kind switch + { + LibraryKindFilter.All => "+e.kind IN ('Post', 'Story', 'Highlight', 'Tagged')", + LibraryKindFilter.Posts => "e.kind = 'Post'", + LibraryKindFilter.Photos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Photo')", + LibraryKindFilter.Videos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Video')", + LibraryKindFilter.Stories => "e.kind = 'Story'", + LibraryKindFilter.Highlights => "(e.kind = 'Highlight' OR EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id))", + LibraryKindFilter.Tagged => "e.kind = 'Tagged'", + LibraryKindFilter.ProfilePictures => "e.kind = 'ProfilePicture'", + _ => throw new ArgumentOutOfRangeException(nameof(filter), filter.Kind, null), + }); + + if (filter.AccountIds is { } accounts) + { + parts.Add($"e.account_id IN ({command.AddList("ac", accounts)})"); + } + + if (filter.From is { } from) + { + parts.Add("e.published_at >= @from"); + command.With("@from", Sql.Time(from)); + } + + if (filter.To is { } to) + { + parts.Add("e.published_at < @to"); + command.With("@to", Sql.Time(to)); + } + + if (filter.Provenance is { } provenance) + { + parts.Add("e.provenance = @prov"); + command.With("@prov", Sql.Enum(provenance)); + } + + var term = TextSearch.Normalize(filter.Search); + if (term.Length > 0) + { + // Accounts are few: match their names here, accent-insensitively, then filter entries by key. + var matching = new List(); + using (var r = c.Command("SELECT id, username, display_name FROM account").ExecuteReader()) + { + while (r.Read()) + { + var name = TextSearch.Normalize(r.GetString(1)); + var display = TextSearch.Normalize(r.GetTextOrNull(2)); + var bare = term.TrimStart('@'); + if (name.Contains(bare, StringComparison.Ordinal) || display.Contains(term, StringComparison.Ordinal)) + { + matching.Add(r.GetInt64(0)); + } + } + } + + command.With("@q", TextSearch.LikePattern(term)); + parts.Add(matching.Count == 0 + ? "e.search_text LIKE @q ESCAPE '\\'" + : $"(e.search_text LIKE @q ESCAPE '\\' OR e.account_id IN ({command.AddList("sa", matching)}))"); + } + + return string.Join(" AND ", parts); + } +} diff --git a/src/Febe.Data/Stores/HighlightStore.cs b/src/Febe.Data/Stores/HighlightStore.cs new file mode 100644 index 0000000..eecfc7e --- /dev/null +++ b/src/Febe.Data/Stores/HighlightStore.cs @@ -0,0 +1,195 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; +using Microsoft.Data.Sqlite; + +namespace Febe.Data.Stores; + +internal sealed class HighlightStore(FebeDatabase db) : IHighlightStore +{ + private const string Columns = "h.id, h.account_id, h.instagram_id, h.title, h.position, h.discovered_at, h.last_checked_at, h.removed_at"; + + private static Highlight Read(SqliteDataReader r) => new() + { + Id = r.GetInt64(0), + AccountId = r.GetInt64(1), + InstagramId = r.GetTextOrNull(2), + Title = r.GetString(3), + Position = r.GetInt32(4), + DiscoveredAt = r.GetTime(5), + LastCheckedAt = r.GetTimeOrNull(6), + RemovedAt = r.GetTimeOrNull(7), + }; + + private static List ReadAll(SqliteCommand command) + { + using var r = command.ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(Read(r)); + } + + return list; + } + + public Task GetAsync(long highlightId, CancellationToken ct = default) => + db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM highlight h WHERE h.id = @id").With("@id", highlightId)).FirstOrDefault(), ct); + + public Task> ListAsync(long accountId, bool includeRemoved = false, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll(c.Command($""" + SELECT {Columns} FROM highlight h WHERE h.account_id = @a {(includeRemoved ? string.Empty : "AND h.removed_at IS NULL")} + ORDER BY h.removed_at IS NOT NULL, h.position, h.id + """).With("@a", accountId)), + ct); + + public Task FindAsync(long accountId, string instagramId, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(instagramId); + return db.ReadAsync( + c => ReadAll(c.Command($"SELECT {Columns} FROM highlight h WHERE h.account_id = @a AND h.instagram_id = @i") + .With("@a", accountId).With("@i", instagramId.Trim())).FirstOrDefault(), + ct); + } + + public Task FindByTitleAsync(long accountId, string title, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(title); + return db.ReadAsync( + c => ReadAll(c.Command($""" + SELECT {Columns} FROM highlight h WHERE h.account_id = @a AND h.title = @t + ORDER BY h.removed_at IS NOT NULL, h.id LIMIT 1 + """).With("@a", accountId).With("@t", title)).FirstOrDefault(), + ct); + } + + public Task UpsertAsync(Highlight highlight, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(highlight); + ArgumentException.ThrowIfNullOrWhiteSpace(highlight.Title); + var instagramId = EntryMapping.NormalizeId(highlight.InstagramId); + return db.WriteAsync( + w => + { + long? id = highlight.Id > 0 ? highlight.Id : null; + if (id is null && instagramId is not null) + { + id = w.Command("SELECT id FROM highlight WHERE account_id = @a AND instagram_id = @i") + .With("@a", highlight.AccountId).With("@i", instagramId).ExecuteScalar() as long?; + } + + if (id is { } existing) + { + var exists = w.Command("SELECT COUNT(*) FROM highlight WHERE id = @id AND account_id = @a") + .With("@id", existing).With("@a", highlight.AccountId).ScalarInt64() > 0; + if (!exists) + { + throw new KeyNotFoundException($"Raccolta {existing} non trovata per l'account {highlight.AccountId}."); + } + + w.Command(""" + UPDATE highlight SET instagram_id = COALESCE(@i, instagram_id), title = @t, position = @p, + last_checked_at = COALESCE(@lc, last_checked_at), removed_at = @r + WHERE id = @id + """) + .With("@i", Sql.Text(instagramId)) + .With("@t", highlight.Title) + .With("@p", (long)highlight.Position) + .With("@lc", Sql.Time(highlight.LastCheckedAt)) + .With("@r", Sql.Time(highlight.RemovedAt)) + .With("@id", existing) + .ExecuteNonQuery(); + } + else + { + w.Command(""" + INSERT INTO highlight (account_id, instagram_id, title, position, discovered_at, last_checked_at, removed_at) + VALUES (@a, @i, @t, @p, @d, @lc, @r) + """) + .With("@a", highlight.AccountId) + .With("@i", Sql.Text(instagramId)) + .With("@t", highlight.Title) + .With("@p", (long)highlight.Position) + .With("@d", Sql.Time(highlight.DiscoveredAt)) + .With("@lc", Sql.Time(highlight.LastCheckedAt)) + .With("@r", Sql.Time(highlight.RemovedAt)) + .ExecuteNonQuery(); + id = w.LastInsertRowId(); + } + + return ReadAll(w.Command($"SELECT {Columns} FROM highlight h WHERE h.id = @id").With("@id", id.Value)).Single(); + }, + ct); + } + + public Task SetOrderAsync(long accountId, IReadOnlyList highlightIdsInOrder, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(highlightIdsInOrder); + return db.WriteAsync( + w => + { + for (var i = 0; i < highlightIdsInOrder.Count; i++) + { + w.Command("UPDATE highlight SET position = @p WHERE id = @id AND account_id = @a") + .With("@p", (long)i).With("@id", highlightIdsInOrder[i]).With("@a", accountId).ExecuteNonQuery(); + } + }, + ct); + } + + public Task MarkRemovedAsync(long highlightId, DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command("UPDATE highlight SET removed_at = COALESCE(removed_at, @at) WHERE id = @id") + .With("@at", Sql.Time(at)).With("@id", highlightId).ExecuteNonQuery(), + ct); + + public Task> ListItemsAsync(long highlightId, CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var r = c.Command("SELECT highlight_id, entry_id, position FROM highlight_entry WHERE highlight_id = @h ORDER BY position, entry_id") + .With("@h", highlightId).ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(new HighlightItem(r.GetInt64(0), r.GetInt64(1), r.GetInt32(2))); + } + + return list; + }, + ct); + + public Task SetItemsAsync(long highlightId, IReadOnlyList entryIdsInOrder, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(entryIdsInOrder); + return db.WriteAsync( + w => + { + w.Command("DELETE FROM highlight_entry WHERE highlight_id = @h").With("@h", highlightId).ExecuteNonQuery(); + var position = 0; + foreach (var entryId in entryIdsInOrder.Distinct()) + { + w.Command("INSERT INTO highlight_entry (highlight_id, entry_id, position) VALUES (@h, @e, @p)") + .With("@h", highlightId).With("@e", entryId).With("@p", (long)position++).ExecuteNonQuery(); + } + }, + ct); + } + + public Task AddItemAsync(long highlightId, long entryId, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command(""" + INSERT INTO highlight_entry (highlight_id, entry_id, position) + VALUES (@h, @e, (SELECT COALESCE(MAX(position) + 1, 0) FROM highlight_entry WHERE highlight_id = @h)) + ON CONFLICT (highlight_id, entry_id) DO NOTHING + """).With("@h", highlightId).With("@e", entryId).ExecuteNonQuery(), + ct); + + public Task> ListForEntryAsync(long entryId, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll(c.Command($""" + SELECT {Columns} FROM highlight h JOIN highlight_entry he ON he.highlight_id = h.id + WHERE he.entry_id = @e ORDER BY h.position, h.id + """).With("@e", entryId)), + ct); +} diff --git a/src/Febe.Data/Stores/ImportStore.cs b/src/Febe.Data/Stores/ImportStore.cs new file mode 100644 index 0000000..2d673af --- /dev/null +++ b/src/Febe.Data/Stores/ImportStore.cs @@ -0,0 +1,311 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; +using Microsoft.Data.Sqlite; + +namespace Febe.Data.Stores; + +internal sealed class ImportStore(FebeDatabase db) : IImportStore +{ + private const string RunColumns = "id, source_path, source_read_only, mode, state, started_at, analyzed_at, completed_at, last_error"; + + private const string FileColumns = + "id, run_id, relative_path, folder, bytes, modified_at, media_kind, content_type, width, height, duration_ms, sha256, phash, " + + "taken_at, date_source, instagram_id, code, probable_account, probable_kind, highlight_title, outcome, matched_media_id, " + + "target_account_id, decision, state, entry_id, destination_path, last_error"; + + private static ImportRun ReadRun(SqliteDataReader r) => new() + { + Id = r.GetInt64(0), + SourcePath = r.GetString(1), + SourceReadOnly = r.GetBool(2), + Mode = r.GetEnum(3), + State = r.GetEnum(4), + StartedAt = r.GetTime(5), + AnalyzedAt = r.GetTimeOrNull(6), + CompletedAt = r.GetTimeOrNull(7), + LastError = r.GetTextOrNull(8), + }; + + private static ImportFile ReadFile(SqliteDataReader r) => new() + { + Id = r.GetInt64(0), + RunId = r.GetInt64(1), + RelativePath = r.GetString(2), + Folder = r.GetString(3), + Bytes = r.GetInt64(4), + ModifiedAt = r.GetTimeOrNull(5), + MediaKind = r.GetEnumOrNull(6), + ContentType = r.GetTextOrNull(7), + Width = r.GetInt32OrNull(8), + Height = r.GetInt32OrNull(9), + Duration = r.GetDurationOrNull(10), + Sha256 = r.GetTextOrNull(11), + PerceptualHash = r.GetHashOrNull(12), + TakenAt = r.GetTimeOrNull(13), + DateSource = r.GetEnumOrNull(14), + InstagramId = r.GetTextOrNull(15), + Code = r.GetTextOrNull(16), + ProbableAccount = r.GetTextOrNull(17), + ProbableKind = r.GetEnumOrNull(18), + HighlightTitle = r.GetTextOrNull(19), + Outcome = r.GetEnum(20), + MatchedMediaId = r.GetInt64OrNull(21), + TargetAccountId = r.GetInt64OrNull(22), + Decision = r.GetEnum(23), + State = r.GetEnum(24), + EntryId = r.GetInt64OrNull(25), + DestinationPath = r.GetTextOrNull(26), + LastError = r.GetTextOrNull(27), + }; + + private static List ReadFiles(SqliteCommand command) + { + using var r = command.ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(ReadFile(r)); + } + + return list; + } + + private static void BindRun(SqliteCommand c, ImportRun run) => + c.With("@source_path", run.SourcePath) + .With("@source_read_only", Sql.Bool(run.SourceReadOnly)) + .With("@mode", Sql.Enum(run.Mode)) + .With("@state", Sql.Enum(run.State)) + .With("@started_at", Sql.Time(run.StartedAt)) + .With("@analyzed_at", Sql.Time(run.AnalyzedAt)) + .With("@completed_at", Sql.Time(run.CompletedAt)) + .With("@last_error", Sql.Text(run.LastError)); + + private static void BindFile(SqliteCommand c, ImportFile f) => + c.With("@run_id", f.RunId) + .With("@relative_path", f.RelativePath) + .With("@folder", f.Folder) + .With("@bytes", f.Bytes) + .With("@modified_at", Sql.Time(f.ModifiedAt)) + .With("@media_kind", Sql.Enum(f.MediaKind)) + .With("@content_type", Sql.Text(f.ContentType)) + .With("@width", Sql.Int(f.Width)) + .With("@height", Sql.Int(f.Height)) + .With("@duration_ms", Sql.Duration(f.Duration)) + .With("@sha256", Sql.Text(f.Sha256?.ToLowerInvariant())) + .With("@phash", Sql.Hash(f.PerceptualHash)) + .With("@taken_at", Sql.Time(f.TakenAt)) + .With("@date_source", Sql.Enum(f.DateSource)) + .With("@instagram_id", Sql.Text(f.InstagramId)) + .With("@code", Sql.Text(f.Code)) + .With("@probable_account", Sql.Text(f.ProbableAccount)) + .With("@probable_kind", Sql.Enum(f.ProbableKind)) + .With("@highlight_title", Sql.Text(f.HighlightTitle)) + .With("@outcome", Sql.Enum(f.Outcome)) + .With("@matched_media_id", Sql.Int(f.MatchedMediaId)) + .With("@target_account_id", Sql.Int(f.TargetAccountId)) + .With("@decision", Sql.Enum(f.Decision)) + .With("@state", Sql.Enum(f.State)) + .With("@entry_id", Sql.Int(f.EntryId)) + .With("@destination_path", Sql.Text(f.DestinationPath)) + .With("@last_error", Sql.Text(f.LastError)); + + public Task CreateRunAsync(ImportRun run, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(run); + ArgumentException.ThrowIfNullOrWhiteSpace(run.SourcePath); + return db.WriteAsync( + w => + { + var c = w.Command(""" + INSERT INTO import_run (source_path, source_read_only, mode, state, started_at, analyzed_at, completed_at, last_error) + VALUES (@source_path, @source_read_only, @mode, @state, @started_at, @analyzed_at, @completed_at, @last_error) + """); + BindRun(c, run); + c.ExecuteNonQuery(); + return run with { Id = w.LastInsertRowId() }; + }, + ct); + } + + public Task UpdateRunAsync(ImportRun run, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(run); + return db.WriteAsync( + w => + { + var c = w.Command(""" + UPDATE import_run SET source_path = @source_path, source_read_only = @source_read_only, mode = @mode, state = @state, + started_at = @started_at, analyzed_at = @analyzed_at, completed_at = @completed_at, last_error = @last_error + WHERE id = @id + """); + BindRun(c, run); + if (c.With("@id", run.Id).ExecuteNonQuery() == 0) + { + throw new KeyNotFoundException($"Importazione {run.Id} non trovata."); + } + }, + ct); + } + + public Task GetRunAsync(long runId, CancellationToken ct = default) => + db.ReadAsync( + c => + { + using var r = c.Command($"SELECT {RunColumns} FROM import_run WHERE id = @id").With("@id", runId).ExecuteReader(); + return r.Read() ? ReadRun(r) : null; + }, + ct); + + public Task> ListRunsAsync(CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var r = c.Command($"SELECT {RunColumns} FROM import_run ORDER BY started_at DESC, id DESC").ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(ReadRun(r)); + } + + return list; + }, + ct); + + public Task AddFilesAsync(IReadOnlyList files, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(files); + return db.WriteAsync( + w => + { + foreach (var file in files) + { + var c = w.Command(""" + INSERT INTO import_file (run_id, relative_path, folder, bytes, modified_at, media_kind, content_type, width, height, + duration_ms, sha256, phash, taken_at, date_source, instagram_id, code, probable_account, probable_kind, + highlight_title, outcome, matched_media_id, target_account_id, decision, state, entry_id, destination_path, last_error) + VALUES (@run_id, @relative_path, @folder, @bytes, @modified_at, @media_kind, @content_type, @width, @height, + @duration_ms, @sha256, @phash, @taken_at, @date_source, @instagram_id, @code, @probable_account, @probable_kind, + @highlight_title, @outcome, @matched_media_id, @target_account_id, @decision, @state, @entry_id, @destination_path, @last_error) + ON CONFLICT (run_id, relative_path) DO NOTHING + """); + BindFile(c, file); + c.ExecuteNonQuery(); + } + }, + ct); + } + + public Task UpdateFileAsync(ImportFile file, CancellationToken ct = default) => UpdateFilesAsync([file], ct); + + public Task UpdateFilesAsync(IReadOnlyList files, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(files); + return db.WriteAsync( + w => + { + foreach (var file in files) + { + var c = w.Command(""" + UPDATE import_file SET relative_path = @relative_path, folder = @folder, bytes = @bytes, modified_at = @modified_at, + media_kind = @media_kind, content_type = @content_type, width = @width, height = @height, duration_ms = @duration_ms, + sha256 = @sha256, phash = @phash, taken_at = @taken_at, date_source = @date_source, instagram_id = @instagram_id, + code = @code, probable_account = @probable_account, probable_kind = @probable_kind, highlight_title = @highlight_title, + outcome = @outcome, matched_media_id = @matched_media_id, target_account_id = @target_account_id, + decision = @decision, state = @state, entry_id = @entry_id, destination_path = @destination_path, last_error = @last_error + WHERE id = @id AND run_id = @run_id + """); + BindFile(c, file); + if (c.With("@id", file.Id).ExecuteNonQuery() == 0) + { + throw new KeyNotFoundException($"File di importazione {file.Id} non trovato."); + } + } + }, + ct); + } + + public Task GetFileAsync(long fileId, CancellationToken ct = default) => + db.ReadAsync(c => ReadFiles(c.Command($"SELECT {FileColumns} FROM import_file WHERE id = @id").With("@id", fileId)).FirstOrDefault(), ct); + + public Task FindFileAsync(long runId, string relativePath, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(relativePath); + return db.ReadAsync( + c => ReadFiles(c.Command($"SELECT {FileColumns} FROM import_file WHERE run_id = @r AND relative_path = @p") + .With("@r", runId).With("@p", relativePath)).FirstOrDefault(), + ct); + } + + public Task> ListFilesAsync(ImportFileQuery query, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(query); + return db.ReadAsync>( + c => ReadFiles(c.Command($""" + SELECT {FileColumns} FROM import_file + WHERE run_id = @r AND id > @after AND (@o IS NULL OR outcome = @o) AND (@s IS NULL OR state = @s) AND (@f IS NULL OR folder = @f) + ORDER BY id LIMIT @limit + """) + .With("@r", query.RunId).With("@after", query.AfterId).With("@o", Sql.Enum(query.Outcome)).With("@s", Sql.Enum(query.State)) + .With("@f", Sql.Text(query.Folder)).With("@limit", (long)Math.Clamp(query.Limit, 1, 10_000))), + ct); + } + + public Task> FindFilesBySha256Async(long runId, string sha256, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(sha256); + return db.ReadAsync>( + c => ReadFiles(c.Command($"SELECT {FileColumns} FROM import_file WHERE run_id = @r AND sha256 = @h ORDER BY id") + .With("@r", runId).With("@h", sha256.Trim().ToLowerInvariant())), + ct); + } + + public Task GetSummaryAsync(long runId, CancellationToken ct = default) => + db.ReadAsync( + c => + { + var byOutcome = Enum.GetValues().ToDictionary(o => o, _ => 0); + var byState = Enum.GetValues().ToDictionary(s => s, _ => 0); + var total = 0; + long bytes = 0; + using var r = c.Command("SELECT outcome, state, COUNT(*), COALESCE(SUM(bytes), 0) FROM import_file WHERE run_id = @r GROUP BY outcome, state") + .With("@r", runId).ExecuteReader(); + while (r.Read()) + { + var count = r.GetInt32(2); + byOutcome[r.GetEnum(0)] += count; + byState[r.GetEnum(1)] += count; + total += count; + bytes += r.GetInt64(3); + } + + return new ImportSummary(total, byOutcome, byState, bytes); + }, + ct); + + public Task> ListFoldersAsync(long runId, CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var r = c.Command(""" + SELECT folder, COUNT(*), MAX(probable_account), MAX(target_account_id) FROM import_file + WHERE run_id = @r GROUP BY folder ORDER BY folder + """).With("@r", runId).ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(new ImportFolder(r.GetString(0), r.GetInt32(1), r.GetTextOrNull(2), r.GetInt64OrNull(3))); + } + + return list; + }, + ct); + + public Task SetFolderTargetAsync(long runId, string folder, long? accountId, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(folder); + return db.WriteAsync( + w => w.Command("UPDATE import_file SET target_account_id = @a WHERE run_id = @r AND folder = @f") + .With("@a", Sql.Int(accountId)).With("@r", runId).With("@f", folder).ExecuteNonQuery(), + ct); + } +} diff --git a/src/Febe.Data/Stores/MediaStore.cs b/src/Febe.Data/Stores/MediaStore.cs new file mode 100644 index 0000000..8937895 --- /dev/null +++ b/src/Febe.Data/Stores/MediaStore.cs @@ -0,0 +1,228 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; +using static Febe.Data.Stores.EntryMapping; + +namespace Febe.Data.Stores; + +internal sealed class MediaStore(FebeDatabase db) : IMediaStore +{ + public Task GetAsync(long mediaId, CancellationToken ct = default) => + db.ReadAsync( + c => + { + using var r = c.Command($"SELECT {MediaColumns} FROM media m WHERE m.id = @id").With("@id", mediaId).ExecuteReader(); + return r.Read() ? ReadMedia(r) : null; + }, + ct); + + public Task> ListByEntryAsync(long entryId, CancellationToken ct = default) => + db.ReadAsync>(c => ReadMediaOf(sql => c.Command(sql), entryId), ct); + + public Task> FindBySha256Async(string sha256, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(sha256); + var key = sha256.Trim().ToLowerInvariant(); + return db.ReadAsync>( + c => + { + using var r = c.Command($""" + SELECT {MediaColumns}, {EntryColumns}, a.username + FROM media m JOIN entry e ON e.id = m.entry_id JOIN account a ON a.id = e.account_id + WHERE m.sha256 = @h ORDER BY m.id + """).With("@h", key).ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(new MediaLocation(ReadMedia(r), ReadEntry(r, MediaColumnCount), r.GetString(MediaColumnCount + EntryColumnCount))); + } + + return list; + }, + ct); + } + + public Task> MapPathsAsync(long accountId, CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var r = c.Command(""" + SELECT m.relative_path, m.entry_id FROM media m JOIN entry e ON e.id = m.entry_id + WHERE e.account_id = @a AND m.relative_path IS NOT NULL + """).With("@a", accountId).ExecuteReader(); + var map = new Dictionary(StringComparer.Ordinal); + while (r.Read()) + { + map[r.GetString(0)] = r.GetInt64(1); + } + + return map; + }, + ct); + + public Task> LoadPerceptualHashesAsync(CancellationToken ct = default) => + db.ReadAsync>( + c => + { + // One pass over media in table order with a key lookup per row: CROSS JOIN keeps media as the outer loop + // and the unary + keeps SQLite off the phash and state indexes, which would turn the pass into random + // reads once ANALYZE statistics exist (several times slower on 200,000 files). + using var r = c.Command(""" + SELECT m.id, e.account_id, m.phash FROM media m CROSS JOIN entry e ON e.id = m.entry_id + WHERE +m.phash IS NOT NULL AND +m.state IN ('Downloaded', 'Imported') + """).ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(new PerceptualHashRecord(r.GetInt64(0), r.GetInt64(1), unchecked((ulong)r.GetInt64(2)))); + } + + return list; + }, + ct); + + public Task> ListPendingDownloadsAsync(int limit, CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var r = c.Command($""" + SELECT {MediaColumns}, e.account_id, e.kind, e.published_at, e.expires_at + FROM media m JOIN entry e ON e.id = m.entry_id + WHERE m.state = 'ToDownload' AND e.state <> 'Deleted' + ORDER BY (e.kind = 'Story') DESC, e.expires_at IS NULL, e.expires_at, e.discovered_at, m.entry_id, m.position + LIMIT @limit + """).With("@limit", (long)Math.Clamp(limit, 1, 10_000)).ExecuteReader(); + var list = new List(); + while (r.Read()) + { + var o = MediaColumnCount; + list.Add(new PendingDownload(ReadMedia(r), r.GetInt64(o), r.GetEnum(o + 1), r.GetTime(o + 2), r.GetTimeOrNull(o + 3))); + } + + return list; + }, + ct); + + public Task CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default) => + db.ReadAsync( + c => + { + var command = accountId is { } a + ? c.Command(""" + SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id + WHERE m.state = 'ToDownload' AND e.state <> 'Deleted' AND e.account_id = @a + """).With("@a", a) + : c.Command(""" + SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id + WHERE m.state = 'ToDownload' AND e.state <> 'Deleted' + """); + return (int)command.ScalarInt64(); + }, + ct); + + public Task MarkStoredAsync(long mediaId, StoredFile file, MediaState state, DateTimeOffset at, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(file); + if (!EntryStateRules.IsPresent(state)) + { + throw new ArgumentException("Un file salvato è «scaricato» o «importato».", nameof(state)); + } + + return db.WriteAsync( + w => + { + var entryId = EntryOf(w, mediaId); + w.Command(""" + UPDATE media SET state = @state, relative_path = @path, bytes = @bytes, sha256 = @sha, phash = @phash, + width = COALESCE(@w, width), height = COALESCE(@h, height), duration_ms = COALESCE(@d, duration_ms), + has_thumbnail = @thumb, downloaded_at = @at, last_error = NULL, source_url = NULL, cover_url = NULL + WHERE id = @id + """) + .With("@state", Sql.Enum(state)) + .With("@path", file.RelativePath) + .With("@bytes", file.Bytes) + .With("@sha", file.Sha256.ToLowerInvariant()) + .With("@phash", Sql.Hash(file.PerceptualHash)) + .With("@w", Sql.Int(file.Width)) + .With("@h", Sql.Int(file.Height)) + .With("@d", Sql.Duration(file.Duration)) + .With("@thumb", Sql.Bool(file.HasThumbnail)) + .With("@at", Sql.Time(at)) + .With("@id", mediaId) + .ExecuteNonQuery(); + RecomputeState(w, entryId, at); + }, + ct); + } + + public Task MarkFailedAsync(long mediaId, MediaState state, string? error, DateTimeOffset at, CancellationToken ct = default) + { + if (state is not (MediaState.Failed or MediaState.Expired or MediaState.Skipped or MediaState.ToDownload)) + { + throw new ArgumentException("Uno scaricamento non riuscito porta a «fallito», «scaduto», «saltato» o di nuovo «da scaricare».", nameof(state)); + } + + return db.WriteAsync( + w => + { + var entryId = EntryOf(w, mediaId); + w.Command("UPDATE media SET state = @state, last_error = @error, attempts = attempts + 1 WHERE id = @id") + .With("@state", Sql.Enum(state)) + .With("@error", Sql.Text(error)) + .With("@id", mediaId) + .ExecuteNonQuery(); + RecomputeState(w, entryId, at); + }, + ct); + } + + public Task UpdateSourceAsync(long mediaId, string? sourceUrl, string? coverUrl, DateTimeOffset seenAt, CancellationToken ct = default) => + db.WriteAsync( + w => + { + var entryId = EntryOf(w, mediaId); + w.Command(""" + UPDATE media SET source_url = @u, cover_url = COALESCE(@c, cover_url), source_seen_at = @at, + state = CASE WHEN state IN ('Expired', 'Failed') THEN 'ToDownload' ELSE state END + WHERE id = @id + """) + .With("@u", Sql.Text(sourceUrl)) + .With("@c", Sql.Text(coverUrl)) + .With("@at", Sql.Time(seenAt)) + .With("@id", mediaId) + .ExecuteNonQuery(); + RecomputeState(w, entryId); + }, + ct); + + public Task SetThumbnailAsync(long mediaId, bool hasThumbnail, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command("UPDATE media SET has_thumbnail = @t WHERE id = @id").With("@t", Sql.Bool(hasThumbnail)).With("@id", mediaId).ExecuteNonQuery(), + ct); + + public Task UpdateAsync(Media media, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(media); + return db.WriteAsync( + w => + { + var entryId = EntryOf(w, media.Id); + var command = w.Command(""" + UPDATE media SET position = @position, kind = @kind, instagram_id = @instagram_id, width = @width, height = @height, + duration_ms = @duration_ms, state = @state, relative_path = @relative_path, bytes = @bytes, sha256 = @sha256, + phash = @phash, has_thumbnail = @has_thumbnail, source_url = @source_url, cover_url = @cover_url, + source_seen_at = @source_seen_at, attempts = @attempts, last_error = @last_error, downloaded_at = @downloaded_at + WHERE id = @id + """); + BindMedia(command, media with { EntryId = entryId }); + command.With("@id", media.Id).ExecuteNonQuery(); + RecomputeState(w, entryId, media.DownloadedAt); + }, + ct); + } + + private static long EntryOf(WriteContext w, long mediaId) + { + var value = w.Command("SELECT entry_id FROM media WHERE id = @id").With("@id", mediaId).ExecuteScalar(); + return value is long entryId ? entryId : throw new KeyNotFoundException($"File {mediaId} non trovato."); + } +} diff --git a/tests/Febe.Tests/Data/AccountStoreTests.cs b/tests/Febe.Tests/Data/AccountStoreTests.cs new file mode 100644 index 0000000..019b01c --- /dev/null +++ b/tests/Febe.Tests/Data/AccountStoreTests.cs @@ -0,0 +1,161 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Tests.Support; + +namespace Febe.Tests.Data; + +[TestClass] +public sealed class AccountStoreTests +{ + [TestMethod] + public async Task AddReadUpdateRoundTripsEveryField() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = Make.Account("studio.lumen.demo", "17841400000000001") with + { + DisplayName = "Studio Lumen", + IsPrivate = true, + IsFollowed = true, + Frequency = Frequency.Custom, + CustomPostInterval = TimeSpan.FromHours(5), + CustomStoryInterval = TimeSpan.FromHours(4), + ContentTypes = ContentTypes.PostPhotos | ContentTypes.Stories, + Limits = new AccountLimits + { + Depth = HistoryDepth.LastPosts, + LastPosts = 500, + BackfillPostsPerDay = 120, + MaxVideoBytes = 200L * 1024 * 1024, + StoryVideos = false, + }, + Folder = "/altrove/studio", + BackfillCursor = "cursore-opaco", + PostCount = 1280, + NextProfileCheckAt = Make.T0.AddHours(3), + }; + + var added = await db.Accounts.AddAsync(account); + Assert.IsGreaterThan(0L, added.Id); + var read = await db.Accounts.GetAsync(added.Id); + Assert.AreEqual(added, read); + + var updated = read! with { Frequency = Frequency.High, CustomPostInterval = null, CustomStoryInterval = null, KeepUpdated = false }; + await db.Accounts.UpdateAsync(updated); + Assert.AreEqual(updated, await db.Accounts.GetAsync(added.Id)); + + Assert.AreEqual(added.Id, (await db.Accounts.FindByInstagramIdAsync("17841400000000001"))!.Id); + Assert.AreEqual(added.Id, (await db.Accounts.FindByUsernameAsync("@Studio.Lumen.Demo"))!.Id); + Assert.IsNull(await db.Accounts.FindByUsernameAsync("nessuno")); + } + + [TestMethod] + public void StartingPointsFollowTheSpecification() + { + var now = new DateTimeOffset(2026, 10, 13, 15, 0, 0, TimeSpan.Zero); + var all = Account.Create("a", StartingPoint.EverythingAndKeepUpdated, now, TestZones.Rome); + Assert.AreEqual(HistoryDepth.All, all.Limits.Depth); + Assert.IsFalse(all.ContentTypes.HasFlag(ContentTypes.Tagged)); + Assert.IsTrue(all.ContentTypes.HasFlag(ContentTypes.ProfilePicture)); + Assert.IsNull(all.Limits.MaxVideoBytes); + Assert.IsTrue(all.Limits.StoryVideos); + Assert.AreEqual(300, all.Limits.BackfillPostsPerDay); + Assert.AreEqual(Frequency.Normal, all.Frequency); + + var mine = Account.Create("tu", StartingPoint.EverythingAndKeepUpdated, now, TestZones.Rome, isMine: true); + Assert.IsTrue(mine.ContentTypes.HasFlag(ContentTypes.Tagged)); + + var fromToday = Account.Create("b", StartingPoint.OnlyNewFromToday, now, TestZones.Rome, CautionProfile.Balanced); + Assert.AreEqual(HistoryDepth.FromDate, fromToday.Limits.Depth); + Assert.AreEqual(new DateTimeOffset(2026, 10, 12, 22, 0, 0, TimeSpan.Zero), fromToday.Limits.FromDate); // local midnight, CEST + Assert.AreEqual(500, fromToday.Limits.BackfillPostsPerDay); + + var stories = Account.Create("c", StartingPoint.OnlyStories, now, TestZones.Rome); + Assert.AreEqual(ContentTypes.Stories | ContentTypes.Highlights, stories.ContentTypes); + Assert.IsTrue(stories.KeepUpdated); + } + + [TestMethod] + public async Task RenameKeepsTheFolderAndRaisesTheNotice() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var layout = new LibraryLayout(temp.Combine("libreria")); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var before = layout.AccountFolder(account); + + await db.Accounts.RenameAsync(account.Id, "marta.nuova", Make.T0); + var renamed = (await db.Accounts.GetAsync(account.Id))!; + + Assert.AreEqual("marta.nuova", renamed.Username); + Assert.AreEqual("marta.demo", renamed.PreviousUsername); + Assert.AreEqual(before, layout.AccountFolder(renamed)); + Assert.IsTrue(renamed.Notices.HasFlag(AccountNotices.Renamed)); + Assert.IsTrue(renamed.NeedsAttention); + + await db.Accounts.ClearNoticesAsync(account.Id, AccountNotices.Renamed); + Assert.IsFalse((await db.Accounts.GetAsync(account.Id))!.NeedsAttention); + } + + [TestMethod] + public async Task StateChecksAndBackfillAreUpdatedInPlace() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + + await db.Accounts.SetStateAsync(account.Id, AccountState.Unreachable, Make.T0.AddHours(1), UnreachableReason.PrivateNotFollowed); + await db.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { LastProfileCheckAt = Make.T0, NextProfileCheckAt = Make.T0.AddHours(3), PostCount = 42, IsPrivate = true }); + await db.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { LastStoriesCheckAt = Make.T0.AddMinutes(5) }); + await db.Accounts.SetBackfillAsync(account.Id, "pagina-7", null); + await db.Accounts.AddNoticesAsync(account.Id, AccountNotices.UnrecognizedFormat, Make.T0.AddHours(2)); + + var read = (await db.Accounts.GetAsync(account.Id))!; + Assert.AreEqual(AccountState.Unreachable, read.State); + Assert.AreEqual(UnreachableReason.PrivateNotFollowed, read.UnreachableReason); + Assert.AreEqual(Make.T0.AddHours(1), read.StateChangedAt); + Assert.AreEqual(Make.T0, read.LastProfileCheckAt); + Assert.AreEqual(Make.T0.AddHours(3), read.NextProfileCheckAt); + Assert.AreEqual(Make.T0.AddMinutes(5), read.LastStoriesCheckAt); + Assert.AreEqual(42, read.PostCount); + Assert.IsTrue(read.IsPrivate); + Assert.AreEqual("pagina-7", read.BackfillCursor); + Assert.AreEqual(Make.T0.AddHours(2), read.FormatUnrecognizedAt); + + await db.Accounts.SetStateAsync(account.Id, AccountState.UpToDate, Make.T0.AddHours(5)); + read = (await db.Accounts.GetAsync(account.Id))!; + Assert.IsNull(read.UnreachableReason); + await Assert.ThrowsExactlyAsync(() => db.Accounts.SetStateAsync(999, AccountState.Paused, Make.T0)); + } + + [TestMethod] + public async Task SummariesAndStatsCountTheLibrary() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo") with { PostCount = 10 }); + await db.Entries.AddAsync(Make.Entry(account.Id, "p1", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(1), "post/a.jpg")]); + await db.Entries.AddAsync(Make.Entry(account.Id, "p2", Make.T0.AddHours(1)), [Make.Stored(Make.Photo(), Make.Sha(2), "post/b.jpg"), Make.Video(2)]); + await db.Entries.AddAsync(Make.Entry(account.Id, "s1", Make.T0, EntryKind.Story) with { DiscoveredAt = Make.T0.AddHours(2) }, [Make.Stored(Make.Video(), Make.Sha(3), "storie/c.mp4")]); + await db.Entries.AddAsync(Make.Entry(account.Id, "pp", Make.T0, EntryKind.ProfilePicture), [Make.Stored(Make.Photo(), Make.Sha(4), "profilo/d.jpg")]); + await db.Entries.AddAsync(Make.Entry(account.Id, "todo", Make.T0), [Make.Photo()]); + await db.Highlights.UpsertAsync(new Highlight { AccountId = account.Id, InstagramId = "h", Title = "Estate", DiscoveredAt = Make.T0 }); + + var summary = (await db.Accounts.ListSummariesAsync(Make.T0.AddHours(1))).Single(); + Assert.AreEqual(3, summary.EntriesInLibrary); + Assert.AreEqual(2, summary.Posts); + Assert.AreEqual(0, summary.NewPostsSince); + Assert.AreEqual(1, summary.NewStoriesSince); + + var stats = await db.Accounts.GetStatsAsync(account.Id); + Assert.AreEqual(2, stats.Posts); + Assert.AreEqual(1, stats.Stories); + Assert.AreEqual(1, stats.ProfilePictures); + Assert.AreEqual(3, stats.EntriesInLibrary); + Assert.AreEqual(1, stats.HighlightCollections); + Assert.AreEqual(4000L, stats.Bytes); + Assert.AreEqual(2, stats.PendingFiles); + Assert.AreEqual(Make.T0.AddHours(1), stats.LastPublishedAt); + } +} diff --git a/tests/Febe.Tests/Data/ConstraintTests.cs b/tests/Febe.Tests/Data/ConstraintTests.cs new file mode 100644 index 0000000..9b9454c --- /dev/null +++ b/tests/Febe.Tests/Data/ConstraintTests.cs @@ -0,0 +1,148 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; +using Febe.Data; +using Febe.Tests.Support; +using Microsoft.Data.Sqlite; + +namespace Febe.Tests.Data; + +[TestClass] +public sealed class ConstraintTests +{ + [TestMethod] + public async Task EntryIsUniquePerAccountKindAndInstagramId() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var marta = await db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var luca = await db.Accounts.AddAsync(Make.Account("luca.demo", "200")); + + var first = await db.Entries.AddAsync(Make.Entry(marta.Id, "555", Make.T0), [Make.Photo()]); + var again = await db.Entries.AddAsync(Make.Entry(marta.Id, "555", Make.T0.AddDays(1), caption: "diversa"), [Make.Photo(), Make.Photo(2)]); + Assert.IsTrue(first.Created); + Assert.IsFalse(again.Created); + Assert.AreEqual(first.Stored.Entry.Id, again.Stored.Entry.Id); + Assert.HasCount(1, again.Stored.Media); + + // Same post as a tagged post of another account, and as another kind: separate entries (spec §8.3). + var tagged = await db.Entries.AddAsync(Make.Entry(luca.Id, "555", Make.T0, EntryKind.Tagged), [Make.Photo()]); + var story = await db.Entries.AddAsync(Make.Entry(marta.Id, "555", Make.T0, EntryKind.Story), [Make.Photo()]); + Assert.IsTrue(tagged.Created); + Assert.IsTrue(story.Created); + + var raw = await Assert.ThrowsExactlyAsync(() => db.WriteAsync( + w => w.Command(""" + INSERT INTO entry (account_id, kind, instagram_id, published_at, state, provenance, discovered_at) + VALUES (@a, 'Post', '555', 0, 'ToDownload', 'Downloaded', 0) + """).With("@a", marta.Id).ExecuteNonQuery(), + default)); + Assert.IsTrue(raw.IsUniqueViolation()); + } + + [TestMethod] + public async Task MediaIsUniquePerEntryAndPosition() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + + await Assert.ThrowsExactlyAsync(() => db.Entries.AddAsync(Make.Entry(account.Id, "1", Make.T0), [Make.Photo(1), Make.Video(1)])); + await Assert.ThrowsExactlyAsync(() => db.Entries.AddAsync(Make.Entry(account.Id, "1", Make.T0), [Make.Photo(0)])); + + var added = await db.Entries.AddAsync(Make.Entry(account.Id, "1", Make.T0), [Make.Photo(1), Make.Video(2)]); + var raw = await Assert.ThrowsExactlyAsync(() => db.WriteAsync( + w => w.Command("INSERT INTO media (entry_id, position, kind, state) VALUES (@e, 2, 'Photo', 'ToDownload')") + .With("@e", added.Stored.Entry.Id).ExecuteNonQuery(), + default)); + Assert.IsTrue(raw.IsUniqueViolation()); + } + + [TestMethod] + public async Task ForeignKeysAreEnforcedAndCascade() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + + var orphan = await Assert.ThrowsExactlyAsync(() => db.WriteAsync( + w => w.Command("INSERT INTO media (entry_id, position, kind, state) VALUES (9999, 1, 'Photo', 'ToDownload')").ExecuteNonQuery(), + default)); + Assert.IsTrue(orphan.IsConstraintViolation()); + + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var entry = await db.Entries.AddAsync(Make.Entry(account.Id, "1", Make.T0), [Make.Photo(1), Make.Photo(2)]); + var highlight = await db.Highlights.UpsertAsync(new Highlight { AccountId = account.Id, InstagramId = "h1", Title = "Estate", DiscoveredAt = Make.T0 }); + await db.Highlights.AddItemAsync(highlight.Id, entry.Stored.Entry.Id); + await db.ActionLog.AppendAsync(new ActionLogRecord { At = Make.T0, Category = Core.Abstractions.ActionKind.ProfileOpen, AccountId = account.Id }); + + await db.Accounts.DeleteAsync(account.Id); + + Assert.IsNull(await db.Entries.GetAsync(entry.Stored.Entry.Id)); + Assert.IsEmpty(await db.Media.ListByEntryAsync(entry.Stored.Entry.Id)); + Assert.IsNull(await db.Highlights.GetAsync(highlight.Id)); + // The action log keeps counting for the budgets: only the account reference goes. + var actions = await db.ActionLog.ListAsync(Make.T0.AddHours(-1), Make.T0.AddHours(1)); + Assert.HasCount(1, actions); + Assert.IsNull(actions[0].AccountId); + } + + [TestMethod] + public async Task AccountInstagramIdAndOwnProfileAreUnique() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + await db.Accounts.AddAsync(Make.Account("tuo.profilo", "1", mine: true)); + + await Assert.ThrowsExactlyAsync(() => db.Accounts.AddAsync(Make.Account("altro", "1"))); + await Assert.ThrowsExactlyAsync(() => db.Accounts.AddAsync(Make.Account("secondo.tu", "2", mine: true))); + + // Archive-only accounts without an identifier can coexist. + await db.Accounts.AddAsync(Make.Account("archivio.uno") with { InstagramId = null, State = AccountState.ArchiveOnly }); + await db.Accounts.AddAsync(Make.Account("archivio.due") with { InstagramId = null, State = AccountState.ArchiveOnly }); + Assert.HasCount(3, await db.Accounts.ListAsync()); + } + + [TestMethod] + public async Task RequiredIndexesExist() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var indexes = await db.ReadAsync( + c => + { + using var r = c.Command("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL").ExecuteReader(); + var list = new List<(string Name, string Table, string Sql)>(); + while (r.Read()) + { + list.Add((r.GetString(0), r.GetString(1), r.GetString(2))); + } + + return list; + }, + default); + + // Spec §8.3: indexes on (account, publication date), SHA-256, perceptual hash, state. + Assert.Contains(i => i.Table == "entry" && i.Sql.Contains("(account_id, published_at)", StringComparison.Ordinal), indexes); + Assert.Contains(i => i.Table == "media" && i.Sql.Contains("(sha256)", StringComparison.Ordinal), indexes); + Assert.Contains(i => i.Table == "media" && i.Sql.Contains("(phash)", StringComparison.Ordinal), indexes); + Assert.Contains(i => i.Table == "entry" && i.Sql.Contains("(state)", StringComparison.Ordinal), indexes); + Assert.Contains(i => i.Table == "media" && i.Sql.Contains("(state)", StringComparison.Ordinal), indexes); + } + + [TestMethod] + public async Task TimesAreStoredInUtc() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var local = new DateTimeOffset(2026, 10, 10, 18, 22, 5, TimeSpan.FromHours(2)); + var added = await db.Entries.AddAsync(Make.Entry(account.Id, "1", local), [Make.Photo()]); + + var raw = await db.ReadAsync(c => c.Command("SELECT published_at FROM entry WHERE id = @id").With("@id", added.Stored.Entry.Id).ScalarInt64(), default); + Assert.AreEqual(new DateTimeOffset(2026, 10, 10, 16, 22, 5, TimeSpan.Zero).ToUnixTimeMilliseconds(), raw); + + var read = await db.Entries.GetAsync(added.Stored.Entry.Id); + Assert.IsNotNull(read); + Assert.AreEqual(local, read.PublishedAt); + Assert.AreEqual(TimeSpan.Zero, read.PublishedAt.Offset); + } +} diff --git a/tests/Febe.Tests/Data/EngineStoreTests.cs b/tests/Febe.Tests/Data/EngineStoreTests.cs new file mode 100644 index 0000000..698bbd3 --- /dev/null +++ b/tests/Febe.Tests/Data/EngineStoreTests.cs @@ -0,0 +1,326 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Storage; +using Febe.Tests.Support; + +namespace Febe.Tests.Data; + +[TestClass] +public sealed class EngineStoreTests +{ + [TestMethod] + public async Task ActionCountsUseARolling60MinuteWindowAndTheLocalDay() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + // now = 13 October 2026, 00:20 in Rome (22:20 UTC on the 12th). + var now = new DateTimeOffset(2026, 10, 12, 22, 20, 0, TimeSpan.Zero); + + async Task Log(ActionKind kind, DateTimeOffset at, long amount = 1) => + await db.ActionLog.AppendAsync(new ActionLogRecord { At = at, Category = kind, AccountId = account.Id, Amount = amount }); + + await Log(ActionKind.ProfileOpen, now.AddMinutes(-60)); // just out of the window; yesterday locally + await Log(ActionKind.ProfileOpen, now.AddMinutes(-59).AddSeconds(-59)); // in the window; yesterday locally (23:20:01) + await Log(ActionKind.ProfileOpen, now.AddMinutes(-15)); // in the window; today (00:05) + await Log(ActionKind.ProfileOpen, now); // now + await Log(ActionKind.StoryView, now.AddMinutes(-5)); + await Log(ActionKind.DataDownload, now.AddMinutes(-1), 5_000_000); + await Log(ActionKind.DataDownload, now.AddMinutes(-90), 1_000_000); // yesterday locally (22:50) + + var usage = await db.ActionLog.GetUsageAsync(now, TestZones.Rome); + Assert.AreEqual(new BudgetUsage(3, 2), usage[ActionKind.ProfileOpen]); + Assert.AreEqual(new BudgetUsage(1, 1), usage[ActionKind.StoryView]); + Assert.AreEqual(new BudgetUsage(5_000_000, 5_000_000), usage[ActionKind.DataDownload]); + Assert.AreEqual(default, usage[ActionKind.Home]); + Assert.HasCount(Enum.GetValues().Length, usage); + + Assert.AreEqual(4L, await db.ActionLog.SumAsync(ActionKind.ProfileOpen, now.AddHours(-2), now.AddSeconds(1), account.Id)); + Assert.AreEqual(0L, await db.ActionLog.SumAsync(ActionKind.ProfileOpen, now.AddHours(-2), now.AddSeconds(1), account.Id + 1)); + Assert.AreEqual(now, await db.ActionLog.GetLastActionAtAsync()); + Assert.AreEqual(now.AddMinutes(-5), await db.ActionLog.GetLastActionAtAsync(ActionKind.StoryView)); + + Assert.AreEqual(2, await db.ActionLog.PruneAsync(now.AddMinutes(-59).AddSeconds(-59))); + Assert.HasCount(5, await db.ActionLog.ListAsync(now.AddDays(-1), now.AddDays(1))); + } + + [TestMethod] + public async Task CountsSurviveARestart() + { + using var temp = new TempFolder(); + await using (var db = await TestDatabase.OpenAsync(temp)) + { + await db.ActionLog.AppendAsync(new ActionLogRecord { At = Make.T0, Category = ActionKind.Home }); + } + + await using (var db = await TestDatabase.OpenAsync(temp)) + { + var usage = await db.ActionLog.GetUsageAsync(Make.T0.AddMinutes(10), TestZones.Rome); + Assert.AreEqual(new BudgetUsage(1, 1), usage[ActionKind.Home]); + } + } + + [TestMethod] + public async Task TaskQueueEnqueuesPeeksAndCompletes() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var now = Make.T0; + + var later = await db.Tasks.EnqueueAsync(new EngineTask { Kind = EngineTaskKind.ProfileCheck, AccountId = account.Id, DueAt = now.AddHours(1), CreatedAt = now }); + var sweep = await db.Tasks.EnqueueAsync(new EngineTask { Kind = EngineTaskKind.FollowingSweep, DueAt = now.AddMinutes(-10), CreatedAt = now }); + var stories = await db.Tasks.EnqueueAsync(new EngineTask { Kind = EngineTaskKind.AccountStories, AccountId = account.Id, DueAt = now.AddMinutes(-5), Priority = 5, CreatedAt = now }); + + // «Controlla ora»: the same pending task moves earlier and up instead of being duplicated. + var manual = await db.Tasks.EnqueueAsync(new EngineTask { Kind = EngineTaskKind.ProfileCheck, AccountId = account.Id, DueAt = now, Priority = 100, IsManual = true, CreatedAt = now }); + Assert.AreEqual(later.Id, manual.Id); + Assert.HasCount(3, await db.Tasks.ListPendingAsync(10)); + + var due = await db.Tasks.PeekDueAsync(now, 10); + Assert.IsTrue(due.Select(t => t.Id).SequenceEqual([manual.Id, stories.Id, sweep.Id])); + Assert.IsTrue(due[0].IsManual); + + Assert.IsTrue(await db.Tasks.TryStartAsync(manual.Id, now)); + Assert.IsFalse(await db.Tasks.TryStartAsync(manual.Id, now), "Un'attività si avvia una volta sola."); + await db.Tasks.CompleteAsync(manual.Id, now.AddMinutes(1)); + Assert.AreEqual(EngineTaskState.Done, (await db.Tasks.GetAsync(manual.Id))!.State); + + Assert.IsTrue(await db.Tasks.TryStartAsync(stories.Id, now)); + await db.Tasks.FailAsync(stories.Id, now, "Rifiutato dal Governatore", now.AddMinutes(30)); + var retried = (await db.Tasks.GetAsync(stories.Id))!; + Assert.AreEqual(EngineTaskState.Pending, retried.State); + Assert.AreEqual(now.AddMinutes(30), retried.DueAt); + Assert.AreEqual(1, retried.Attempts); + + Assert.IsTrue(await db.Tasks.TryStartAsync(sweep.Id, now)); + Assert.AreEqual(1, await db.Tasks.RequeueRunningAsync()); + Assert.AreEqual(EngineTaskState.Pending, (await db.Tasks.GetAsync(sweep.Id))!.State); + + Assert.AreEqual(1, await db.Tasks.CancelForAccountAsync(account.Id, now)); + await db.Tasks.FailAsync(sweep.Id, now, "Errore", null); + Assert.AreEqual(EngineTaskState.Failed, (await db.Tasks.GetAsync(sweep.Id))!.State); + Assert.IsEmpty(await db.Tasks.ListPendingAsync(10)); + Assert.AreEqual(3, await db.Tasks.PurgeFinishedAsync(now.AddDays(1))); + } + + [TestMethod] + public async Task SessionsIncidentsAndEvents() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + + var first = await db.Sessions.StartAsync(Make.T0); + await db.Sessions.EndAsync(first.Id, Make.T0.AddMinutes(6), SessionOutcome.Completed, 14, "Giro e storie"); + var second = await db.Sessions.StartAsync(Make.T0.AddHours(1)); + Assert.AreEqual(second.Id, (await db.Sessions.GetLastAsync())!.Id); + Assert.HasCount(2, await db.Sessions.ListAsync(Make.T0.AddMinutes(5), Make.T0.AddHours(2))); + Assert.HasCount(1, await db.Sessions.ListAsync(Make.T0.AddMinutes(30), Make.T0.AddHours(2))); + Assert.AreEqual(1, await db.Sessions.CloseInterruptedAsync(Make.T0.AddHours(3))); + Assert.AreEqual(SessionOutcome.Interrupted, (await db.Sessions.GetAsync(second.Id))!.Outcome); + + var throttle = await db.Incidents.OpenAsync(new Incident { At = Make.T0, Level = SignalLevel.Throttle, Signal = "http-429", Url = "https://www.instagram.com/x/", StoppedUntil = Make.T0.AddHours(1), SessionId = first.Id }); + await db.Incidents.OpenAsync(new Incident { At = Make.T0.AddDays(-3), Level = SignalLevel.Throttle, Signal = "http-429" }); + var challenge = await db.Incidents.OpenAsync(new Incident { At = Make.T0.AddHours(2), Level = SignalLevel.Challenge, Signal = "challenge-url" }); + await db.Incidents.ResolveAsync(throttle.Id, Make.T0.AddHours(1)); + Assert.HasCount(2, await db.Incidents.ListOpenAsync()); + Assert.AreEqual(2, await db.Incidents.CountAsync(SignalLevel.Throttle, Make.T0.AddDays(-7))); + Assert.AreEqual(1, await db.Incidents.CountAsync(SignalLevel.Throttle, Make.T0.AddHours(-24))); + Assert.IsTrue((await db.Incidents.GetAsync(challenge.Id))!.IsOpen); + Assert.HasCount(2, await db.Incidents.ListAsync(Make.T0, Make.T0.AddDays(1))); + + for (var i = 0; i < 12; i++) + { + await db.Events.AppendAsync(new EventRecord + { + At = Make.T0.AddMinutes(i), + Code = "prova", + Message = $"Evento {i}", + Severity = i % 4 == 0 ? EventSeverity.Warning : EventSeverity.Info, + AccountId = i % 2 == 0 ? account.Id : null, + }); + } + + var page1 = await db.Events.ListAsync(new EventQuery { Limit = 5 }); + var page2 = await db.Events.ListAsync(new EventQuery { Limit = 5, BeforeId = page1[^1].Id }); + Assert.IsTrue(page1.Concat(page2).Select(e => e.Message).SequenceEqual(Enumerable.Range(2, 10).Reverse().Select(i => $"Evento {i}"))); + Assert.HasCount(6, await db.Events.ListAsync(new EventQuery { AccountId = account.Id })); + Assert.HasCount(3, await db.Events.ListAsync(new EventQuery { MinSeverity = EventSeverity.Warning })); + var after = await db.Events.ListAfterAsync(page1[1].Id); + Assert.IsTrue(after.Select(e => e.Message).SequenceEqual(["Evento 11"])); + Assert.AreEqual(3, await db.Events.PruneAsync(Make.T0.AddMinutes(3))); + } + + [TestMethod] + public async Task FollowingListIsReadOverSeveralSessions() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var read1 = Make.T0; + await db.Following.UpsertAsync([ + new FollowingRecord { InstagramId = "1", Username = "marta.demo", Position = 0, ReadAt = read1 }, + new FollowingRecord { InstagramId = "2", Username = "luca.demo", Position = 1, ReadAt = read1, IsPrivate = true }, + ]); + await db.Following.UpsertAsync([new FollowingRecord { Username = "senza.id", Position = 2, ReadAt = read1 }]); + Assert.AreEqual(3, await db.Following.CountAsync()); + + // A new complete read: marta renamed, luca unfollowed. + var read2 = Make.T0.AddDays(2); + await db.Following.UpsertAsync([ + new FollowingRecord { InstagramId = "1", Username = "marta.nuova", Position = 0, ReadAt = read2 }, + new FollowingRecord { Username = "senza.id", DisplayName = "Senza", Position = 1, ReadAt = read2 }, + ]); + Assert.AreEqual(1, await db.Following.RemoveNotReadSinceAsync(read2)); + var list = await db.Following.ListAsync(); + Assert.IsTrue(list.Select(f => f.Username).SequenceEqual(["marta.nuova", "senza.id"])); + Assert.AreEqual(read2, await db.Following.GetLastReadAtAsync()); + await db.Following.ClearAsync(); + Assert.AreEqual(0, await db.Following.CountAsync()); + } + + [TestMethod] + public async Task HighlightsKeepTheirOrderAndContents() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var e1 = (await db.Entries.AddAsync(Make.Entry(account.Id, "1", Make.T0, EntryKind.Highlight), [Make.Photo()])).Stored.Entry.Id; + var e2 = (await db.Entries.AddAsync(Make.Entry(account.Id, "2", Make.T0, EntryKind.Story), [Make.Photo()])).Stored.Entry.Id; + + var summer = await db.Highlights.UpsertAsync(new Highlight { AccountId = account.Id, InstagramId = "h1", Title = "Estate", Position = 0, DiscoveredAt = Make.T0 }); + var food = await db.Highlights.UpsertAsync(new Highlight { AccountId = account.Id, InstagramId = "h2", Title = "Cucina", Position = 1, DiscoveredAt = Make.T0 }); + var renamed = await db.Highlights.UpsertAsync(new Highlight { AccountId = account.Id, InstagramId = "h1", Title = "Estate 2025", Position = 0, DiscoveredAt = Make.T0 }); + Assert.AreEqual(summer.Id, renamed.Id); + + await db.Highlights.SetOrderAsync(account.Id, [food.Id, summer.Id]); + Assert.IsTrue((await db.Highlights.ListAsync(account.Id)).Select(h => h.Title).SequenceEqual(["Cucina", "Estate 2025"])); + + await db.Highlights.SetItemsAsync(summer.Id, [e2, e1]); + await db.Highlights.AddItemAsync(summer.Id, e1); + await db.Highlights.AddItemAsync(food.Id, e1); + Assert.IsTrue((await db.Highlights.ListItemsAsync(summer.Id)).Select(i => i.EntryId).SequenceEqual([e2, e1])); + Assert.HasCount(2, await db.Highlights.ListForEntryAsync(e1)); + + await db.Highlights.MarkRemovedAsync(food.Id, Make.T0.AddDays(1)); + Assert.HasCount(1, await db.Highlights.ListAsync(account.Id)); + Assert.HasCount(2, await db.Highlights.ListAsync(account.Id, includeRemoved: true)); + Assert.AreEqual(food.Id, (await db.Highlights.FindByTitleAsync(account.Id, "Cucina"))!.Id); + } + + [TestMethod] + public async Task DuplicatePairsWaitForADecision() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var a = (await db.Entries.AddAsync(Make.Entry(account.Id, "1", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(1), "a.jpg")])).Stored.Media[0]; + var b = (await db.Entries.AddAsync(Make.Entry(account.Id, "2", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(2), "b.jpg")])).Stored.Media[0]; + + var pair = new DuplicatePair { Origin = DuplicateOrigin.Download, Reason = DuplicateReason.VisuallySimilar, ExistingMediaId = a.Id, CandidateMediaId = b.Id, Distance = 4, CreatedAt = Make.T0 }; + var stored = await db.Duplicates.AddAsync(pair); + var again = await db.Duplicates.AddAsync(pair); + Assert.AreEqual(stored.Id, again.Id); + Assert.AreEqual(1, await db.Duplicates.CountPendingAsync()); + Assert.AreEqual(0, await db.Duplicates.CountPendingAsync(DuplicateOrigin.Import)); + + await Assert.ThrowsExactlyAsync(() => db.Duplicates.AddAsync(pair with { CandidateImportFileId = 1 })); + + await db.Duplicates.DecideAsync(stored.Id, DuplicateDecision.KeepBoth, Make.T0.AddHours(1)); + Assert.IsEmpty(await db.Duplicates.ListPendingAsync()); + var decided = (await db.Duplicates.GetAsync(stored.Id))!; + Assert.AreEqual(DuplicateDecision.KeepBoth, decided.Decision); + Assert.AreEqual(Make.T0.AddHours(1), decided.DecidedAt); + } + + [TestMethod] + public async Task ImportsResumeAndAssociateFolders() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var run = await db.Imports.CreateRunAsync(new ImportRun { SourcePath = "/importa/stogram", SourceReadOnly = true, StartedAt = Make.T0 }); + + ImportFile File(string path, string folder) => new() { RunId = run.Id, RelativePath = path, Folder = folder, Bytes = 100 }; + await db.Imports.AddFilesAsync([File("marta/a.jpg", "marta"), File("marta/b.jpg", "marta"), File("altro/c.mp4", "altro")]); + await db.Imports.AddFilesAsync([File("marta/a.jpg", "marta") with { Bytes = 999 }]); // resumed analysis: unchanged + var a = (await db.Imports.FindFileAsync(run.Id, "marta/a.jpg"))!; + Assert.AreEqual(100L, a.Bytes); + + await db.Imports.UpdateFileAsync(a with + { + Sha256 = Make.Sha(5), + MediaKind = MediaKind.Photo, + PerceptualHash = ulong.MaxValue, + Outcome = ImportOutcome.New, + State = ImportFileState.Analyzed, + ProbableAccount = "marta.demo", + ProbableKind = EntryKind.Story, + TakenAt = Make.T0, + DateSource = ImportDateSource.FileName, + }); + var b = (await db.Imports.FindFileAsync(run.Id, "marta/b.jpg"))!; + await db.Imports.UpdateFilesAsync([b with { Sha256 = Make.Sha(5), Outcome = ImportOutcome.ProbableDuplicate, State = ImportFileState.Analyzed }]); + + Assert.HasCount(2, await db.Imports.FindFilesBySha256Async(run.Id, Make.Sha(5))); + var reread = (await db.Imports.GetFileAsync(a.Id))!; + Assert.AreEqual(ulong.MaxValue, reread.PerceptualHash); + Assert.AreEqual(EntryKind.Story, reread.ProbableKind); + + await db.Imports.SetFolderTargetAsync(run.Id, "marta", account.Id); + var folders = await db.Imports.ListFoldersAsync(run.Id); + Assert.HasCount(2, folders); + Assert.AreEqual(new ImportFolder("marta", 2, "marta.demo", account.Id), folders.Single(f => f.Folder == "marta")); + + var summary = await db.Imports.GetSummaryAsync(run.Id); + Assert.AreEqual(3, summary.Total); + Assert.AreEqual(1, summary.ByOutcome[ImportOutcome.New]); + Assert.AreEqual(1, summary.ByOutcome[ImportOutcome.Pending]); + Assert.AreEqual(2, summary.ByState[ImportFileState.Analyzed]); + Assert.AreEqual(300L, summary.Bytes); + + var pendingOnly = await db.Imports.ListFilesAsync(new ImportFileQuery { RunId = run.Id, State = ImportFileState.Pending }); + Assert.AreEqual("altro/c.mp4", pendingOnly.Single().RelativePath); + + await db.Imports.UpdateRunAsync(run with { State = ImportRunState.Reviewing, AnalyzedAt = Make.T0.AddMinutes(5) }); + Assert.AreEqual(ImportRunState.Reviewing, (await db.Imports.GetRunAsync(run.Id))!.State); + Assert.HasCount(1, await db.Imports.ListRunsAsync()); + } + + [TestMethod] + public async Task SettingsStoreAndLibrarySettings() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + await db.Settings.SetAsync("a", "1"); + await db.Settings.SetAsync("a", "2"); + await db.Settings.SetBoolAsync("b", true); + await db.Settings.SetInt64Async("c", 42); + Assert.AreEqual("2", await db.Settings.GetAsync("a")); + Assert.IsTrue(await db.Settings.GetBoolAsync("b", false)); + Assert.AreEqual(42L, await db.Settings.GetInt64Async("c")); + await db.Settings.SetAsync("a", null); + Assert.IsNull(await db.Settings.GetAsync("a")); + + var defaults = await Core.Library.LibrarySettings.LoadAsync(db.Settings, "/libreria"); + Assert.AreEqual("/libreria", defaults.LibraryRoot); + Assert.AreEqual(Core.Library.NamingScheme.DefaultGeneral, defaults.Naming.General.Text); + Assert.IsTrue(defaults.SetFileTimeToPublication); + + var custom = defaults with + { + LibraryRoot = "/altrove", + Naming = defaults.Naming with { General = Core.Library.NamingScheme.Parse(@"{account}\{tipo}\{data}_{codice}_{n}", false) }, + SetFileTimeToPublication = false, + }; + await custom.SaveAsync(db.Settings); + var loaded = await Core.Library.LibrarySettings.LoadAsync(db.Settings, "/libreria"); + Assert.AreEqual("/altrove", loaded.LibraryRoot); + Assert.AreEqual(@"{account}\{tipo}\{data}_{codice}_{n}", loaded.Naming.General.Text); + Assert.IsFalse(loaded.SetFileTimeToPublication); + + await db.Settings.SetAsync(SettingKeys.NamingScheme, "{sconosciuto}"); + var fallback = await Core.Library.LibrarySettings.LoadAsync(db.Settings, "/libreria"); + Assert.AreEqual(Core.Library.NamingScheme.DefaultGeneral, fallback.Naming.General.Text); + } +} diff --git a/tests/Febe.Tests/Data/EntryStoreTests.cs b/tests/Febe.Tests/Data/EntryStoreTests.cs new file mode 100644 index 0000000..ca2ad67 --- /dev/null +++ b/tests/Febe.Tests/Data/EntryStoreTests.cs @@ -0,0 +1,300 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; +using Febe.Data; +using Febe.Tests.Support; + +namespace Febe.Tests.Data; + +[TestClass] +public sealed class EntryStoreTests +{ + [TestMethod] + public async Task KnownIdentifiersIncludeDeletedEntries() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var kept = await db.Entries.AddAsync(Make.Entry(account.Id, "1", Make.T0), [Make.Photo()]); + var deleted = await db.Entries.AddAsync(Make.Entry(account.Id, "2", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(2), "post/x.jpg")]); + var removed = await db.Entries.AddAsync(Make.Entry(account.Id, "3", Make.T0), [Make.Photo()]); + + await db.Entries.MarkDeletedAsync(deleted.Stored.Entry.Id, Make.T0.AddDays(1)); + await db.Entries.RemoveAsync(removed.Stored.Entry.Id); + + Assert.IsTrue(await db.Entries.IsKnownAsync(account.Id, EntryKind.Post, "1")); + Assert.IsTrue(await db.Entries.IsKnownAsync(account.Id, EntryKind.Post, "2"), "Un elemento eliminato resta noto e non si riscarica."); + Assert.IsFalse(await db.Entries.IsKnownAsync(account.Id, EntryKind.Post, "3"), "«Lascia che torni» toglie il record."); + Assert.IsFalse(await db.Entries.IsKnownAsync(account.Id, EntryKind.Story, "1")); + + var known = await db.Entries.GetKnownInstagramIdsAsync(account.Id, EntryKind.Post, ["1", "2", "3", "4", " 1 "]); + Assert.IsTrue(known.SetEquals(["1", "2"])); + + var deletedRead = (await db.Entries.GetWithMediaAsync(deleted.Stored.Entry.Id))!; + Assert.AreEqual(EntryState.Deleted, deletedRead.Entry.State); + Assert.AreEqual(Make.T0.AddDays(1), deletedRead.Entry.DeletedAt); + Assert.AreEqual(MediaState.Deleted, deletedRead.Media[0].State); + Assert.IsNull(deletedRead.Media[0].RelativePath); + Assert.AreEqual(Make.Sha(2), deletedRead.Media[0].Sha256); + Assert.AreEqual(kept.Stored.Entry.Id, (await db.Entries.FindAsync(account.Id, EntryKind.Post, "1"))!.Id); + } + + [TestMethod] + public async Task FindsEntriesByIdentifierAcrossKindsAndByPublicationTime() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + await db.Entries.AddAsync(Make.Entry(account.Id, "77", Make.T0, EntryKind.Story), [Make.Photo()]); + await db.Entries.AddAsync(Make.Entry(account.Id, "77", Make.T0, EntryKind.Highlight), [Make.Photo()]); + var imported = await db.Entries.AddAsync( + Make.Entry(account.Id, "x", Make.T0.AddMinutes(30)) with { InstagramId = null, Provenance = Provenance.Imported }, + [Make.Photo(1, MediaState.Imported) with { Sha256 = Make.Sha(9), RelativePath = "importati/a.jpg" }]); + + Assert.HasCount(2, await db.Entries.FindByInstagramIdAsync(account.Id, "77")); + Assert.AreEqual(EntryState.Imported, imported.Stored.Entry.State); + + var match = await db.Entries.FindByPublicationTimeAsync(account.Id, EntryKind.Post, Make.T0.AddMinutes(30).AddMilliseconds(1500), TimeSpan.FromSeconds(2)); + Assert.AreEqual(imported.Stored.Entry.Id, match?.Id); + Assert.IsNull(await db.Entries.FindByPublicationTimeAsync(account.Id, EntryKind.Post, Make.T0.AddMinutes(30).AddSeconds(3), TimeSpan.FromSeconds(2))); + + // Recognized later: Instagram data is added to the existing entry (spec §9.5). + await db.Entries.UpdateAsync(imported.Stored.Entry with { InstagramId = "888", Code = "Abc", Caption = "Ritrovata" }); + Assert.IsTrue(await db.Entries.IsKnownAsync(account.Id, EntryKind.Post, "888")); + } + + [TestMethod] + public async Task StateFollowsTheFiles() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var added = await db.Entries.AddAsync(Make.Entry(account.Id, "1", Make.T0), [Make.Photo(1), Make.Video(2)]); + var photo = added.Stored.Media[0]; + var video = added.Stored.Media[1]; + Assert.AreEqual(EntryState.ToDownload, added.Stored.Entry.State); + + await db.Media.MarkStoredAsync(photo.Id, new StoredFile("post/2026/a_1.jpg", 1234, Make.Sha(1), 0xABCDEFUL, 1080, 1350, null, true), MediaState.Downloaded, Make.T0.AddMinutes(1)); + Assert.AreEqual(EntryState.Partial, (await db.Entries.GetAsync(added.Stored.Entry.Id))!.State); + + await db.Media.MarkFailedAsync(video.Id, MediaState.Expired, "Indirizzo scaduto", Make.T0.AddMinutes(2)); + var afterExpiry = (await db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!; + Assert.AreEqual(EntryState.Partial, afterExpiry.Entry.State); + Assert.AreEqual(1, afterExpiry.Media[1].Attempts); + + await db.Media.UpdateSourceAsync(video.Id, "https://cdn.example/v.mp4", null, Make.T0.AddMinutes(3)); + Assert.AreEqual(MediaState.ToDownload, (await db.Media.GetAsync(video.Id))!.State); + + await db.Media.MarkStoredAsync(video.Id, new StoredFile("post/2026/a_2.mp4", 99, Make.Sha(2), Duration: TimeSpan.FromSeconds(12)), MediaState.Downloaded, Make.T0.AddMinutes(4)); + var done = (await db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!; + Assert.AreEqual(EntryState.Downloaded, done.Entry.State); + Assert.AreEqual(Make.T0.AddMinutes(4), done.Entry.DownloadedAt); + Assert.IsNull(done.Media[1].SourceUrl, "L'indirizzo firmato non resta nel database dopo lo scaricamento."); + Assert.AreEqual(0xABCDEFUL, done.Media[0].PerceptualHash); + Assert.AreEqual(TimeSpan.FromSeconds(12), done.Media[1].Duration); + + Assert.AreEqual(EntryState.Skipped, EntryStateRules.FromMedia(EntryState.ToDownload, Provenance.Downloaded, [MediaState.Skipped])); + Assert.AreEqual(EntryState.Failed, EntryStateRules.FromMedia(EntryState.ToDownload, Provenance.Downloaded, [MediaState.Failed, MediaState.Skipped])); + Assert.AreEqual(EntryState.Deleted, EntryStateRules.FromMedia(EntryState.Deleted, Provenance.Downloaded, [MediaState.Downloaded])); + } + + [TestMethod] + public async Task ExactDuplicatesAreFoundAcrossTheLibrary() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var marta = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var luca = await db.Accounts.AddAsync(Make.Account("luca.demo")); + await db.Entries.AddAsync(Make.Entry(marta.Id, "1", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(7), "post/a.jpg") with { PerceptualHash = 5 }]); + await db.Entries.AddAsync(Make.Entry(luca.Id, "1", Make.T0, EntryKind.Tagged), [Make.Stored(Make.Photo(), Make.Sha(7).ToUpperInvariant(), "taggati/a.jpg")]); + await db.Entries.AddAsync(Make.Entry(luca.Id, "2", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(8), "post/b.jpg") with { PerceptualHash = 6 }]); + + var found = await db.Media.FindBySha256Async(Make.Sha(7).ToUpperInvariant()); + Assert.HasCount(2, found); + Assert.IsTrue(found.Select(f => f.Username).Order().SequenceEqual(["luca.demo", "marta.demo"])); + + var hashes = await db.Media.LoadPerceptualHashesAsync(); + Assert.HasCount(2, hashes); + Assert.Contains(new PerceptualHashRecord(found.Single(f => f.Username == "marta.demo").Media.Id, marta.Id, 5), hashes); + } + + [TestMethod] + public async Task DownloadQueueGivesStoriesPrecedence() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var a = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var b = await db.Accounts.AddAsync(Make.Account("luca.demo")); + await db.Entries.AddAsync(Make.Entry(a.Id, "post", Make.T0), [Make.Photo(1), Make.Photo(2)]); + await db.Entries.AddAsync(Make.Entry(b.Id, "storia-tardi", Make.T0, EntryKind.Story) with { ExpiresAt = Make.T0.AddHours(20) }, [Make.Video()]); + await db.Entries.AddAsync(Make.Entry(b.Id, "storia-presto", Make.T0, EntryKind.Story) with { ExpiresAt = Make.T0.AddHours(2) }, [Make.Video()]); + var gone = await db.Entries.AddAsync(Make.Entry(a.Id, "eliminato", Make.T0), [Make.Photo()]); + await db.Entries.MarkDeletedAsync(gone.Stored.Entry.Id, Make.T0); + + var queue = await db.Media.ListPendingDownloadsAsync(10); + Assert.HasCount(4, queue); + Assert.AreEqual(EntryKind.Story, queue[0].Kind); + Assert.AreEqual(Make.T0.AddHours(2), queue[0].ExpiresAt); + Assert.AreEqual(EntryKind.Story, queue[1].Kind); + Assert.AreEqual(1, queue[2].Media.Position); + Assert.AreEqual(2, queue[3].Media.Position); + Assert.AreEqual(2, await db.Media.CountPendingDownloadsAsync(a.Id)); + Assert.AreEqual(4, await db.Media.CountPendingDownloadsAsync()); + } + + [TestMethod] + public async Task LibraryPagesWithKeysetInBothDirections() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var items = Enumerable.Range(0, 25) + .Select(i => new NewEntry(Make.Entry(account.Id, $"e{i}", Make.T0.AddMinutes(i % 10 == 0 ? 0 : i)), [Make.Stored(Make.Photo(), Make.Sha(i + 1), $"post/{i}.jpg")])) + .ToList(); + await db.Entries.AddManyAsync(items); + + var seen = new List(); + var page = await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 7 }); + Assert.IsNull(page.Newer); + while (true) + { + seen.AddRange(page.Tiles.Select(t => t.EntryId)); + if (page.Older is not { } older) + { + break; + } + + page = await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 7, Cursor = older }); + Assert.IsNotNull(page.Newer); + } + + Assert.HasCount(25, seen); + Assert.AreEqual(25, seen.Distinct().Count()); + var all = await db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Limit = 100 }); + Assert.IsTrue(all.Select(e => e.Id).SequenceEqual(seen), "Stesso ordine: data di pubblicazione decrescente, poi chiave."); + + // Going back up from the middle returns the newer window, still in display order. + var middle = new LibraryCursor(all[12].PublishedAt, all[12].Id); + var newer = await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 5, Cursor = middle, Direction = LibraryDirection.Newer }); + Assert.IsTrue(newer.Tiles.Select(t => t.EntryId).SequenceEqual(all.Skip(7).Take(5).Select(e => e.Id))); + Assert.IsNotNull(newer.Newer); + Assert.IsNotNull(newer.Older); + + var jump = await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 3, Cursor = LibraryCursor.At(Make.T0.AddMinutes(5)) }); + Assert.IsTrue(jump.Tiles.All(t => t.PublishedAt <= Make.T0.AddMinutes(5))); + } + + [TestMethod] + public async Task LibraryFiltersByKindAccountPeriodProvenanceAndSearch() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var marta = await db.Accounts.AddAsync(Make.Account("marta.demo") with { DisplayName = "Marta Bianchi" }); + var luca = await db.Accounts.AddAsync(Make.Account("luca.viaggi.demo")); + var photoPost = await Add(db, marta.Id, "foto", EntryKind.Post, Make.T0, "Perché no? Tramonto a Genova", Make.Photo()); + var videoPost = await Add(db, marta.Id, "video", EntryKind.Post, Make.T0.AddHours(1), "Reel della domenica", Make.Video()); + var mixed = await Add(db, luca.Id, "misto", EntryKind.Post, Make.T0.AddHours(2), "50% sconto_estate", Make.Photo(), Make.Video(2)); + var story = await Add(db, luca.Id, "storia", EntryKind.Story, Make.T0.AddHours(3), null, Make.Video()); + var highlightItem = await Add(db, luca.Id, "evid", EntryKind.Highlight, Make.T0.AddHours(4), null, Make.Photo()); + var tagged = await Add(db, marta.Id, "tag", EntryKind.Tagged, Make.T0.AddHours(5), "Con @amica", Make.Photo()); + var profile = await Add(db, marta.Id, "profilo", EntryKind.ProfilePicture, Make.T0.AddHours(6), null, Make.Photo()); + var imported = await db.Entries.AddAsync( + Make.Entry(marta.Id, "imp", Make.T0.AddDays(-30)) with { Provenance = Provenance.Imported }, + [Make.Photo(1, MediaState.Imported) with { Sha256 = Make.Sha(99), RelativePath = "importati/x.jpg" }]); + var pending = await db.Entries.AddAsync(Make.Entry(marta.Id, "attesa", Make.T0), [Make.Photo()]); + + // The story is also referenced by a highlight collection (H9). + var collection = await db.Highlights.UpsertAsync(new Highlight { AccountId = luca.Id, InstagramId = "h1", Title = "Viaggi", DiscoveredAt = Make.T0 }); + await db.Highlights.SetItemsAsync(collection.Id, [highlightItem, story]); + + async Task Ids(LibraryFilter filter) => + (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = filter, Limit = 100 })).Tiles.Select(t => t.EntryId).Order().ToArray(); + static long[] Of(params long[] ids) => ids.Order().ToArray(); + + CollectionAssert.AreEqual(Of(photoPost, videoPost, mixed, story, highlightItem, tagged, imported.Stored.Entry.Id), await Ids(new LibraryFilter())); + CollectionAssert.AreEqual(Of(photoPost, mixed, imported.Stored.Entry.Id), await Ids(new LibraryFilter { Kind = LibraryKindFilter.Photos })); + CollectionAssert.AreEqual(Of(videoPost, mixed), await Ids(new LibraryFilter { Kind = LibraryKindFilter.Videos })); + CollectionAssert.AreEqual(Of(story), await Ids(new LibraryFilter { Kind = LibraryKindFilter.Stories })); + CollectionAssert.AreEqual(Of(story, highlightItem), await Ids(new LibraryFilter { Kind = LibraryKindFilter.Highlights })); + CollectionAssert.AreEqual(Of(tagged), await Ids(new LibraryFilter { Kind = LibraryKindFilter.Tagged })); + CollectionAssert.AreEqual(Of(profile), await Ids(new LibraryFilter { Kind = LibraryKindFilter.ProfilePictures })); + CollectionAssert.AreEqual(Of(mixed, story, highlightItem), await Ids(new LibraryFilter { AccountIds = [luca.Id] })); + CollectionAssert.AreEqual(Of(videoPost, mixed), await Ids(new LibraryFilter { From = Make.T0.AddHours(1), To = Make.T0.AddHours(3) })); + CollectionAssert.AreEqual(Of(imported.Stored.Entry.Id), await Ids(new LibraryFilter { Provenance = Provenance.Imported })); + CollectionAssert.AreEqual(Of(pending.Stored.Entry.Id), await Ids(new LibraryFilter { States = [EntryState.ToDownload] })); + + // Search: caption without accents or case, literal % and _, user name, display name. + CollectionAssert.AreEqual(Of(photoPost), await Ids(new LibraryFilter { Search = "PERCHE" })); + CollectionAssert.AreEqual(Of(mixed), await Ids(new LibraryFilter { Search = "50%" })); + CollectionAssert.AreEqual(Of(mixed), await Ids(new LibraryFilter { Search = "o_e" })); + CollectionAssert.AreEqual(Of(mixed, story, highlightItem), await Ids(new LibraryFilter { Search = "@luca.viaggi" })); + CollectionAssert.AreEqual(Of(photoPost, videoPost, tagged, imported.Stored.Entry.Id), await Ids(new LibraryFilter { Search = "bianchi" })); + CollectionAssert.AreEqual(Of(tagged), await Ids(new LibraryFilter { Search = "amica", Kind = LibraryKindFilter.Tagged })); + Assert.IsEmpty(await Ids(new LibraryFilter { Search = "nessuna corrispondenza" })); + + var totals = await db.Entries.GetLibraryTotalsAsync(new LibraryFilter()); + Assert.AreEqual(new LibraryTotals(7, 2), totals); + + var tiles = (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { AccountIds = [luca.Id], Kind = LibraryKindFilter.Posts } })).Tiles; + var tile = tiles.Single(); + Assert.AreEqual(2, tile.MediaCount); + Assert.AreEqual(MediaKind.Photo, tile.CoverKind); + Assert.AreEqual("luca.viaggi.demo", tile.Username); + var ordered = await db.Entries.GetTilesAsync([story, photoPost, 999]); + Assert.IsTrue(ordered.Select(t => t.EntryId).SequenceEqual([story, photoPost])); + } + + [TestMethod] + public async Task CountsPerLocalDayFollowAlbertosZone() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + // 22:30 UTC on 12 October is 00:30 on 13 October in Rome (CEST, +2). + await Add(db, account.Id, "a", EntryKind.Post, new DateTimeOffset(2026, 10, 12, 22, 30, 0, TimeSpan.Zero), null, Make.Photo()); + await Add(db, account.Id, "b", EntryKind.Post, new DateTimeOffset(2026, 10, 12, 21, 59, 0, TimeSpan.Zero), null, Make.Photo()); + await Add(db, account.Id, "c", EntryKind.Story, new DateTimeOffset(2026, 10, 13, 21, 45, 0, TimeSpan.Zero), null, Make.Photo()); + // 25 October 2026: clocks go back. 23:15 UTC is 00:15 on 26 October in Rome (CET, +1). + await Add(db, account.Id, "d", EntryKind.Post, new DateTimeOffset(2026, 10, 25, 23, 15, 0, TimeSpan.Zero), null, Make.Photo()); + await Add(db, account.Id, "e", EntryKind.Post, new DateTimeOffset(2026, 10, 25, 22, 45, 0, TimeSpan.Zero), null, Make.Photo()); + + var days = await db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome); + CollectionAssert.AreEqual( + new[] + { + new DayCount(new DateOnly(2026, 10, 26), 1), + new DayCount(new DateOnly(2026, 10, 25), 1), + new DayCount(new DateOnly(2026, 10, 13), 2), + new DayCount(new DateOnly(2026, 10, 12), 1), + }, + days.ToArray()); + + var stories = await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Kind = LibraryKindFilter.Stories }, TestZones.Rome); + CollectionAssert.AreEqual(new[] { new DayCount(new DateOnly(2026, 10, 13), 1) }, stories.ToArray()); + } + + [TestMethod] + public async Task AccountListPagesAndDailyDiscoveryCount() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + for (var i = 0; i < 10; i++) + { + await db.Entries.AddAsync(Make.Entry(account.Id, $"p{i}", Make.T0.AddDays(-i)) with { DiscoveredAt = Make.T0.AddMinutes(i) }, [Make.Photo()]); + } + + var first = await db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 4 }); + var next = await db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 4, Before = new LibraryCursor(first[^1].PublishedAt, first[^1].Id) }); + Assert.IsTrue(first.Concat(next).Select(e => e.InstagramId).SequenceEqual(Enumerable.Range(0, 8).Select(i => $"p{i}"))); + Assert.AreEqual(5, await db.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, Make.T0, Make.T0.AddMinutes(5))); + } + + private static int shaCounter = 1000; + + private static async Task Add(FebeDatabase db, long accountId, string id, EntryKind kind, DateTimeOffset at, string? caption, params Media[] media) + { + var stored = media.Select((m, i) => m with { State = MediaState.Downloaded, Sha256 = Make.Sha(Interlocked.Increment(ref shaCounter)), RelativePath = $"x/{id}_{i}" }).ToList(); + var result = await db.Entries.AddAsync(Make.Entry(accountId, id, at, kind, caption), stored); + return result.Stored.Entry.Id; + } +} diff --git a/tests/Febe.Tests/Data/LibraryScaleTests.cs b/tests/Febe.Tests/Data/LibraryScaleTests.cs new file mode 100644 index 0000000..2685d30 --- /dev/null +++ b/tests/Febe.Tests/Data/LibraryScaleTests.cs @@ -0,0 +1,131 @@ +using System.Diagnostics; +using Febe.Core.Domain; +using Febe.Core.Storage; +using Febe.Data; +using Febe.Tests.Support; + +namespace Febe.Tests.Data; + +/// Spec §4.6: the library must stay fluid with 200,000 entries. +[TestClass] +public sealed class LibraryScaleTests +{ + private const int Entries = 200_000; + private const int Accounts = 40; + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task LibraryQueriesStayFastWith200000Entries() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var accountIds = new List(); + for (var a = 0; a < Accounts; a++) + { + accountIds.Add((await db.Accounts.AddAsync(Make.Account($"account{a:00}.demo", $"{1000 + a}"))).Id); + } + + var words = new[] { "mare", "montagna", "città", "tramonto", "cena", "amici", "viaggio", "festa", "libro", "caffè" }; + var random = new Random(7); + var start = new DateTimeOffset(2016, 1, 1, 0, 0, 0, TimeSpan.Zero); + var span = (long)(new DateTimeOffset(2026, 10, 13, 0, 0, 0, TimeSpan.Zero) - start).TotalSeconds; + var fill = Stopwatch.StartNew(); + for (var batch = 0; batch < Entries / 5000; batch++) + { + var items = new List(5000); + for (var i = 0; i < 5000; i++) + { + var n = (batch * 5000) + i; + var kind = (n % 10) switch { 0 or 1 => EntryKind.Story, 2 => EntryKind.Highlight, 3 => EntryKind.Tagged, _ => EntryKind.Post }; + var caption = string.Join(' ', Enumerable.Range(0, 12).Select(_ => words[random.Next(words.Length)])) + (n == 123_456 ? " parolarara" : string.Empty); + var media = new List { Make.Stored(n % 7 == 0 ? Make.Video() : Make.Photo() with { PerceptualHash = (ulong)n * 0x9E3779B97F4A7C15UL }, Make.Sha(n + 1), $"x/{n}.jpg") }; + if (n % 5 == 0) + { + media.Add(Make.Stored(Make.Photo(2), Make.Sha(n + 10_000_000), $"x/{n}_2.jpg")); + } + + items.Add(new NewEntry( + Make.Entry(accountIds[n % Accounts], $"id{n}", start.AddSeconds(random.NextInt64(span)), kind, caption) with { Provenance = n % 13 == 0 ? Provenance.Imported : Provenance.Downloaded }, + media)); + } + + await db.Entries.AddManyAsync(items); + } + + fill.Stop(); + TestContext.WriteLine($"Riempimento: {Entries:N0} elementi in {fill.Elapsed.TotalSeconds:F1} s"); + + // Plans differ with and without ANALYZE statistics: both must be fast. + await MeasureAll(db, accountIds, "senza statistiche"); + await db.WriteAsync(w => w.Command("ANALYZE").ExecuteNonQuery(), default); + await MeasureAll(db, accountIds, "con ANALYZE"); + } + + private async Task MeasureAll(FebeDatabase db, List accountIds, string label) + { + var times = new Dictionary(); + async Task Measure(string name, Func> query) + { + await query(); // warm the page cache + var best = double.MaxValue; + T result = default!; + for (var run = 0; run < 3; run++) + { + var watch = Stopwatch.StartNew(); + result = await query(); + best = Math.Min(best, watch.Elapsed.TotalMilliseconds); + } + + times[name] = best; + return result; + } + + var first = await Measure("prima finestra", () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200 })); + Assert.HasCount(200, first.Tiles); + var middleCursor = LibraryCursor.At(new DateTimeOffset(2021, 6, 1, 0, 0, 0, TimeSpan.Zero)); + var middle = await Measure("finestra a metà (salto a una data)", () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Cursor = middleCursor })); + Assert.HasCount(200, middle.Tiles); + Assert.IsTrue(middle.Tiles.All(t => t.PublishedAt < middleCursor.PublishedAt)); + await Measure("finestra più recente da metà", () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Cursor = middleCursor, Direction = LibraryDirection.Newer })); + await Measure("filtro Video", () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { Kind = LibraryKindFilter.Videos } })); + await Measure("filtro Storie", () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { Kind = LibraryKindFilter.Stories } })); + await Measure("filtro In evidenza", () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { Kind = LibraryKindFilter.Highlights } })); + await Measure("filtro un account", () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { AccountIds = [accountIds[3]] } })); + await Measure("filtro tre account", () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { AccountIds = [accountIds[3], accountIds[9], accountIds[30]] } })); + await Measure("filtro periodo e provenienza", () => db.Entries.QueryLibraryAsync(new LibraryQuery + { + Limit = 200, + Filter = new LibraryFilter { From = new DateTimeOffset(2020, 1, 1, 0, 0, 0, TimeSpan.Zero), To = new DateTimeOffset(2020, 2, 1, 0, 0, 0, TimeSpan.Zero), Provenance = Provenance.Imported }, + })); + var rare = await Measure("ricerca rara nella didascalia", () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { Search = "PAROLARARA" } })); + Assert.HasCount(1, rare.Tiles); + await Measure("ricerca comune", () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { Search = "caffe" } })); + await Measure("ricerca per account", () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { Search = "account07" } })); + var totals = await Measure("totali", () => db.Entries.GetLibraryTotalsAsync(new LibraryFilter())); + Assert.AreEqual(new LibraryTotals(Entries, Accounts), totals); + var days = await Measure("conteggi per giorno", () => db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome)); + Assert.AreEqual(Entries, days.Sum(d => d.Count)); + await Measure("è già noto? (pagina di 12)", async () => await db.Entries.GetKnownInstagramIdsAsync(accountIds[5], EntryKind.Post, Enumerable.Range(0, 12).Select(i => $"id{5 + (i * 40)}").ToList())); + await Measure("SHA-256 in tutta la libreria", () => db.Media.FindBySha256Async(Make.Sha(150_001))); + var summaries = await Measure("elenco account con conteggi", () => db.Accounts.ListSummariesAsync(new DateTimeOffset(2026, 10, 1, 0, 0, 0, TimeSpan.Zero))); + Assert.AreEqual(Entries, summaries.Sum(s => s.EntriesInLibrary)); + await Measure("scheda account", () => db.Accounts.GetStatsAsync(accountIds[2])); + await Measure("coda degli scaricamenti", () => db.Media.ListPendingDownloadsAsync(50)); + var hashes = await Measure("caricamento impronte", () => db.Media.LoadPerceptualHashesAsync()); + Assert.IsGreaterThan(150_000, hashes.Count); + + foreach (var (name, ms) in times) + { + TestContext.WriteLine($"[{label}] {name,-40} {ms,8:F1} ms"); + } + + // Bounds with room for a slower CI runner and for tests running in parallel; measured values are ~10× lower. + foreach (var (name, ms) in times) + { + var heavy = name.StartsWith("ricerca", StringComparison.Ordinal) || name.StartsWith("conteggi", StringComparison.Ordinal) + || name.StartsWith("totali", StringComparison.Ordinal) || name.StartsWith("caricamento", StringComparison.Ordinal); + Assert.IsLessThan(heavy ? 1500.0 : 250.0, ms, $"[{label}] {name}"); + } + } +} diff --git a/tests/Febe.Tests/Data/MigrationTests.cs b/tests/Febe.Tests/Data/MigrationTests.cs new file mode 100644 index 0000000..5effee4 --- /dev/null +++ b/tests/Febe.Tests/Data/MigrationTests.cs @@ -0,0 +1,161 @@ +using Febe.Data; +using Febe.Tests.Support; +using Microsoft.Data.Sqlite; + +namespace Febe.Tests.Data; + +[TestClass] +public sealed class MigrationTests +{ + private static readonly string[] Tables = + [ + "setting", "account", "entry", "media", "highlight", "highlight_entry", "duplicate_pair", "task", "action_log", + "session", "incident", "event", "following", "import_run", "import_file", + ]; + + [TestMethod] + public void EmbeddedMigrationsAreNumberedFromOne() + { + var migrations = MigrationRunner.LoadEmbedded(); + Assert.IsNotEmpty(migrations); + for (var i = 0; i < migrations.Count; i++) + { + Assert.AreEqual(i + 1, migrations[i].Version); + } + + Assert.AreEqual("schema", migrations[0].Name); + } + + [TestMethod] + public void NumberingWithGapsIsRefused() + { + Assert.ThrowsExactly(() => MigrationRunner.Validate([new Migration(1, "a", "SELECT 1"), new Migration(3, "c", "SELECT 1")])); + Assert.ThrowsExactly(() => MigrationRunner.Validate([new Migration(1, "a", "SELECT 1"), new Migration(1, "b", "SELECT 1")])); + } + + [TestMethod] + public async Task FreshDatabaseHasEveryTableAndTheLatestVersion() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + + Assert.AreEqual(MigrationRunner.LoadEmbedded().Count, db.SchemaVersion); + Assert.AreEqual(Path.Combine(temp.Combine("dati"), FebeDatabase.FileName), db.DatabasePath); + var tables = await db.ReadAsync( + c => + { + using var r = c.Command("SELECT name FROM sqlite_master WHERE type = 'table'").ExecuteReader(); + var names = new List(); + while (r.Read()) + { + names.Add(r.GetString(0)); + } + + return names; + }, + default); + foreach (var table in Tables) + { + Assert.Contains(table, tables); + } + + var version = await db.ReadAsync(c => c.Command("PRAGMA user_version").ScalarInt64(), default); + Assert.AreEqual((long)db.SchemaVersion, version); + } + + [TestMethod] + public async Task DatabaseUsesWalForeignKeysAndBusyTimeout() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + + var mode = await db.ReadAsync(c => (string)c.Command("PRAGMA journal_mode").ExecuteScalar()!, default); + Assert.AreEqual("wal", mode); + var foreignKeys = await db.WriteAsync(w => w.Command("PRAGMA foreign_keys").ScalarInt64(), default); + Assert.AreEqual(1L, foreignKeys); + var timeout = await db.WriteAsync(w => w.Command("PRAGMA busy_timeout").ScalarInt64(), default); + Assert.IsGreaterThanOrEqualTo(5000L, timeout); + } + + [TestMethod] + public async Task ReopeningKeepsDataAndDoesNotRerunMigrations() + { + using var temp = new TempFolder(); + await using (var db = await TestDatabase.OpenAsync(temp)) + { + await db.Settings.SetAsync("prova", "1"); + } + + await using (var db = await TestDatabase.OpenAsync(temp)) + { + Assert.AreEqual("1", await db.Settings.GetAsync("prova")); + Assert.AreEqual(MigrationRunner.LoadEmbedded().Count, db.SchemaVersion); + } + } + + [TestMethod] + public async Task NewerDatabaseIsRefusedAndLeftUntouched() + { + using var temp = new TempFolder(); + var path = temp.Combine("dati", FebeDatabase.FileName); + await using (var db = await TestDatabase.OpenAsync(temp)) + { + await db.Settings.SetAsync("prova", "1"); + } + + SetUserVersion(path, 99); + var error = await Assert.ThrowsExactlyAsync(() => FebeDatabase.OpenFileAsync(path)); + Assert.Contains("più recente", error.Message); + Assert.AreEqual(99L, GetUserVersion(path)); + } + + [TestMethod] + public void FailingMigrationRollsBackEntirely() + { + using var temp = new TempFolder(); + var path = temp.Combine("dati", FebeDatabase.FileName); + var good = MigrationRunner.LoadEmbedded(); + var broken = good.Append(new Migration(good.Count + 1, "rotta", "CREATE TABLE extra (id INTEGER); INSERT INTO nowhere VALUES (1);")).ToList(); + + Assert.ThrowsExactly(() => FebeDatabase.Open(path, broken)); + + Assert.AreEqual((long)good.Count, GetUserVersion(path)); + using var connection = new SqliteConnection($"Data Source={path};Pooling=False"); + connection.Open(); + Assert.AreEqual(0L, connection.Command("SELECT COUNT(*) FROM sqlite_master WHERE name = 'extra'").ScalarInt64()); + } + + [TestMethod] + public void MigrationAddingDataAppliesOnTopOfTheSchema() + { + using var temp = new TempFolder(); + var path = temp.Combine("dati", FebeDatabase.FileName); + var good = MigrationRunner.LoadEmbedded(); + var next = good.Append(new Migration(good.Count + 1, "dati", "INSERT INTO setting (key, value) VALUES ('migrata', 'si');")).ToList(); + + var db = FebeDatabase.Open(path, next); + try + { + Assert.AreEqual(good.Count + 1, db.SchemaVersion); + Assert.AreEqual("si", db.Settings.GetAsync("migrata").GetAwaiter().GetResult()); + } + finally + { + db.DisposeAsync().AsTask().GetAwaiter().GetResult(); + } + } + + private static void SetUserVersion(string path, int version) + { + using var connection = new SqliteConnection($"Data Source={path};Pooling=False"); + connection.Open(); + connection.Command($"PRAGMA user_version = {version}").ExecuteNonQuery(); + } + + private static long GetUserVersion(string path) + { + using var connection = new SqliteConnection($"Data Source={path};Pooling=False"); + connection.Open(); + return connection.Command("PRAGMA user_version").ScalarInt64(); + } +} diff --git a/tests/Febe.Tests/Data/SingleWriterTests.cs b/tests/Febe.Tests/Data/SingleWriterTests.cs new file mode 100644 index 0000000..78ee00e --- /dev/null +++ b/tests/Febe.Tests/Data/SingleWriterTests.cs @@ -0,0 +1,144 @@ +using System.Diagnostics; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Data; +using Febe.Tests.Support; +using Microsoft.Data.Sqlite; + +namespace Febe.Tests.Data; + +[TestClass] +public sealed class SingleWriterTests +{ + [TestMethod] + public async Task ConcurrentWritesAreSerializedAndAllCommitted() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + const int writers = 24; + const int perWriter = 50; + + using var stopReaders = new CancellationTokenSource(); + var readers = Enumerable.Range(0, 4).Select(_ => Task.Run(async () => + { + var reads = 0; + while (!stopReaders.IsCancellationRequested) + { + await db.ActionLog.SumAsync(ActionKind.StoryView, Make.T0.AddDays(-1), Make.T0.AddDays(1)); + reads++; + } + + return reads; + })).ToList(); + + var tasks = Enumerable.Range(0, writers).Select(w => Task.Run(async () => + { + for (var i = 0; i < perWriter; i++) + { + await db.ActionLog.AppendAsync(new ActionLogRecord + { + At = Make.T0.AddSeconds((w * perWriter) + i), + Category = ActionKind.StoryView, + AccountId = account.Id, + }); + } + })); + await Task.WhenAll(tasks); + await stopReaders.CancelAsync(); + var readCounts = await Task.WhenAll(readers); + + var total = await db.ActionLog.SumAsync(ActionKind.StoryView, Make.T0.AddDays(-1), Make.T0.AddDays(1)); + Assert.AreEqual((long)writers * perWriter, total); + Assert.AreEqual(1, db.Writer.MaxObservedConcurrency, "Le scritture devono passare una alla volta."); + Assert.IsTrue(readCounts.All(c => c > 0), "Le letture proseguono mentre si scrive."); + } + + [TestMethod] + public async Task WritesRunOnTheWriterThread() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var threads = await Task.WhenAll(Enumerable.Range(0, 20).Select(_ => Task.Run(() => db.WriteAsync(_ => Environment.CurrentManagedThreadId, default)))); + Assert.IsTrue(threads.All(t => t == db.Writer.ThreadId)); + } + + [TestMethod] + public async Task AFailingWriteDoesNotUndoTheOthers() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + using var gate = new ManualResetEventSlim(false); + + // Hold the writer so that the next writes are queued together and share one transaction. + var blocker = db.WriteAsync(_ => gate.Wait(TimeSpan.FromSeconds(10)), default); + var good1 = db.Settings.SetAsync("a", "1"); + var bad = db.WriteAsync(w => w.Command("INSERT INTO media (entry_id, position, kind, state) VALUES (424242, 1, 'Photo', 'ToDownload')").ExecuteNonQuery(), default); + var good2 = db.Settings.SetAsync("b", "2"); + gate.Set(); + + await blocker; + await good1; + await good2; + await Assert.ThrowsExactlyAsync(() => bad); + Assert.AreEqual("1", await db.Settings.GetAsync("a")); + Assert.AreEqual("2", await db.Settings.GetAsync("b")); + } + + [TestMethod] + public async Task AWriteCancelledWhileQueuedIsNotExecuted() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + using var gate = new ManualResetEventSlim(false); + using var cancel = new CancellationTokenSource(); + + var blocker = db.WriteAsync(_ => gate.Wait(TimeSpan.FromSeconds(10)), default); + var cancelled = db.Settings.SetAsync("annullata", "1", cancel.Token); + await cancel.CancelAsync(); + gate.Set(); + await blocker; + + await Assert.ThrowsAsync(() => cancelled); + await db.Settings.SetAsync("dopo", "1"); + Assert.IsNull(await db.Settings.GetAsync("annullata")); + } + + [TestMethod] + public async Task ReadsAreNotBlockedByALongWrite() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + await db.Settings.SetAsync("prima", "1"); + using var gate = new ManualResetEventSlim(false); + + var longWrite = db.WriteAsync( + w => + { + w.Command("INSERT INTO setting (key, value) VALUES ('durante', '1')").ExecuteNonQuery(); + gate.Wait(TimeSpan.FromSeconds(10)); + }, + default); + + var watch = Stopwatch.StartNew(); + var value = await db.Settings.GetAsync("prima"); + var during = await db.Settings.GetAsync("durante"); + watch.Stop(); + gate.Set(); + await longWrite; + + Assert.AreEqual("1", value); + Assert.IsNull(during, "Una lettura non vede una scrittura non ancora confermata."); + Assert.IsLessThan(2000L, watch.ElapsedMilliseconds); + Assert.AreEqual("1", await db.Settings.GetAsync("durante")); + } + + [TestMethod] + public async Task WritesAfterDisposeFail() + { + using var temp = new TempFolder(); + var db = await TestDatabase.OpenAsync(temp); + await db.DisposeAsync(); + await Assert.ThrowsExactlyAsync(() => db.Settings.SetAsync("x", "1")); + } +} diff --git a/tests/Febe.Tests/Library/AccountJournalTests.cs b/tests/Febe.Tests/Library/AccountJournalTests.cs new file mode 100644 index 0000000..d0aa5e5 --- /dev/null +++ b/tests/Febe.Tests/Library/AccountJournalTests.cs @@ -0,0 +1,116 @@ +using System.Text; +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Library; + +[TestClass] +public sealed class AccountJournalTests +{ + [TestMethod] + public async Task SaveAndDeleteLinesAreAppendedAndReadBack() + { + using var temp = new TempFolder(); + var clock = new ManualClock(Make.T0); + var journal = new AccountJournal(clock); + var account = Make.Account("marta.demo", "100") with { DisplayName = "Marta B." }; + var entry = Make.Entry(1, "3742118", Make.T0.AddHours(-2), EntryKind.Highlight, "Però che bella giornata") with { Code = null }; + var media = new[] + { + Make.Stored(Make.Photo(1), Make.Sha(1), "evidenza/Estate 2025/a_1.jpg"), + Make.Video(2), // not downloaded: not in the line + }; + + await journal.AppendSavedAsync(temp.Path, account, entry, media, [new JournalHighlight("h1", "Estate 2025", 0)]); + clock.Now = Make.T0.AddDays(1); + await journal.AppendDeletedAsync(temp.Path, account, entry, ["evidenza/Estate 2025/a_1.jpg"], remember: true); + + var text = await File.ReadAllTextAsync(AccountJournal.PathFor(temp.Path)); + Assert.Contains("Però", text, "Gli accenti restano leggibili."); + Assert.AreEqual(2, text.Count(c => c == '\n')); + + var content = await AccountJournal.ReadAsync(temp.Path); + Assert.AreEqual(0, content.InvalidLines); + Assert.HasCount(2, content.Lines); + + var save = content.Lines[0]; + Assert.AreEqual(JournalOps.Save, save.Op); + Assert.AreEqual(1, save.V); + Assert.AreEqual(Make.T0, save.At); + Assert.AreEqual("100", save.Account.Id); + Assert.AreEqual("marta.demo", save.Account.Username); + Assert.AreEqual("evidenza", save.Entry.Kind); + Assert.AreEqual(EntryKind.Highlight, save.Kind); + Assert.AreEqual("3742118", save.Entry.Id); + Assert.AreEqual("Però che bella giornata", save.Entry.Caption); + Assert.AreEqual(Make.T0.AddHours(-2), save.Entry.PublishedAt); + Assert.AreEqual("Estate 2025", save.Entry.Highlights!.Single().Title); + var file = save.Files!.Single(); + Assert.AreEqual(1, file.N); + Assert.AreEqual("photo", file.Type); + Assert.AreEqual("evidenza/Estate 2025/a_1.jpg", file.Path); + Assert.AreEqual(Make.Sha(1), file.Sha256); + + var delete = content.Lines[1]; + Assert.AreEqual(JournalOps.Delete, delete.Op); + Assert.IsTrue(delete.Remember); + Assert.IsNull(delete.Entry.Caption, "Una riga di eliminazione non ripete la didascalia."); + Assert.AreEqual("evidenza/Estate 2025/a_1.jpg", delete.Files!.Single().Path); + } + + [TestMethod] + public async Task TheJournalIsOnlyAppendedNeverRewritten() + { + using var temp = new TempFolder(); + var journal = new AccountJournal(new ManualClock(Make.T0)); + var account = Make.Account("marta.demo"); + await journal.AppendSavedAsync(temp.Path, account, Make.Entry(1, "1", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(1), "post/a.jpg")]); + var before = await File.ReadAllBytesAsync(AccountJournal.PathFor(temp.Path)); + + await journal.AppendSavedAsync(temp.Path, account, Make.Entry(1, "2", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(2), "post/b.jpg")]); + await journal.AppendDeletedAsync(temp.Path, account, Make.Entry(1, "1", Make.T0), ["post/a.jpg"], remember: false); + var after = await File.ReadAllBytesAsync(AccountJournal.PathFor(temp.Path)); + + Assert.IsGreaterThan(before.Length, after.Length); + CollectionAssert.AreEqual(before, after.Take(before.Length).ToArray()); + } + + [TestMethod] + public async Task ALineCutByACrashDoesNotSpoilTheNextOnes() + { + using var temp = new TempFolder(); + var journal = new AccountJournal(new ManualClock(Make.T0)); + var account = Make.Account("marta.demo"); + await journal.AppendSavedAsync(temp.Path, account, Make.Entry(1, "1", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(1), "post/a.jpg")]); + await File.AppendAllTextAsync(AccountJournal.PathFor(temp.Path), "{\"v\":1,\"op\":\"save\",\"at\":\"2026-", Encoding.UTF8); + await journal.AppendSavedAsync(temp.Path, account, Make.Entry(1, "2", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(2), "post/b.jpg")]); + + var content = await AccountJournal.ReadAsync(temp.Path); + Assert.AreEqual(1, content.InvalidLines); + Assert.IsTrue(content.Lines.Select(l => l.Entry.Id).SequenceEqual(["1", "2"])); + } + + [TestMethod] + public async Task ParallelAppendsKeepEveryLineWhole() + { + using var temp = new TempFolder(); + var journal = new AccountJournal(new ManualClock(Make.T0)); + var account = Make.Account("marta.demo"); + await Task.WhenAll(Enumerable.Range(0, 100).Select(i => Task.Run(() => + journal.AppendSavedAsync(temp.Path, account, Make.Entry(1, $"e{i}", Make.T0, caption: new string('x', 3000)), [Make.Stored(Make.Photo(), Make.Sha(i), $"post/{i}.jpg")])))); + + var content = await AccountJournal.ReadAsync(temp.Path); + Assert.AreEqual(0, content.InvalidLines); + Assert.AreEqual(100, content.Lines.Select(l => l.Entry.Id).Distinct().Count()); + } + + [TestMethod] + public async Task AMissingJournalIsEmpty() + { + using var temp = new TempFolder(); + var content = await AccountJournal.ReadAsync(temp.Combine("nessuno")); + Assert.IsEmpty(content.Lines); + Assert.AreEqual(0, content.InvalidLines); + } +} diff --git a/tests/Febe.Tests/Library/DailyBackupTests.cs b/tests/Febe.Tests/Library/DailyBackupTests.cs new file mode 100644 index 0000000..b818be1 --- /dev/null +++ b/tests/Febe.Tests/Library/DailyBackupTests.cs @@ -0,0 +1,96 @@ +using Febe.Core.Library; +using Febe.Tests.Support; +using Microsoft.Data.Sqlite; + +namespace Febe.Tests.Library; + +[TestClass] +public sealed class DailyBackupTests +{ + [TestMethod] + public async Task MakesOneConsistentCopyPerLocalDay() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + await db.Accounts.AddAsync(Make.Account("marta.demo")); + // 23:30 UTC on 12 October is already the 13th in Rome. + var clock = new ManualClock(new DateTimeOffset(2026, 10, 12, 23, 30, 0, TimeSpan.Zero)); + var backup = new DailyBackup(db.Maintenance, clock, temp.Combine("dati", "copie")); + + var first = await backup.RunAsync(); + Assert.IsNotNull(first.Created); + Assert.AreEqual(new DateOnly(2026, 10, 13), first.Created.Day); + Assert.AreEqual("febe-2026-10-13.sqlite", Path.GetFileName(first.Created.Path)); + + using (var connection = new SqliteConnection($"Data Source={first.Created.Path};Mode=ReadOnly;Pooling=False")) + { + connection.Open(); + using var command = connection.CreateCommand(); + command.CommandText = "SELECT username FROM account"; + Assert.AreEqual("marta.demo", command.ExecuteScalar()); + } + + await db.Accounts.AddAsync(Make.Account("luca.demo")); + clock.Now = clock.Now.AddHours(12); + var second = await backup.RunAsync(); + Assert.IsNull(second.Created, "La copia del giorno c'è già."); + Assert.HasCount(1, backup.List()); + Assert.IsEmpty(Directory.GetFiles(backup.Folder, "*.part")); + } + + [TestMethod] + public async Task KeepsSevenDays() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var folder = temp.Combine("dati", "copie"); + Directory.CreateDirectory(folder); + var today = new DateOnly(2026, 10, 13); + for (var i = 1; i <= 10; i++) + { + await File.WriteAllTextAsync(Path.Combine(folder, DailyBackup.FileNameFor(today.AddDays(-i))), "vecchia"); + } + + await File.WriteAllTextAsync(Path.Combine(folder, "appunti.txt"), "non toccare"); + await File.WriteAllTextAsync(Path.Combine(folder, "febe-2026-10-13.sqlite.abcd1234.part"), "copia interrotta"); + + var clock = new ManualClock(LibraryTimes.Noon(today)); + var backup = new DailyBackup(db.Maintenance, clock, folder); + var result = await backup.RunAsync(); + + Assert.IsNotNull(result.Created); + var kept = backup.List().Select(b => b.Day).ToList(); + Assert.HasCount(7, kept); + Assert.AreEqual(today, kept[0]); + Assert.AreEqual(today.AddDays(-6), kept[^1]); + Assert.HasCount(5, result.Removed); // four old copies and the interrupted one + Assert.IsTrue(File.Exists(Path.Combine(folder, "appunti.txt"))); + } + + [TestMethod] + public void RecognizesOnlyItsOwnFileNames() + { + Assert.AreEqual(new DateOnly(2026, 1, 2), DailyBackup.TryParseDay("febe-2026-01-02.sqlite")); + Assert.IsNull(DailyBackup.TryParseDay("febe-2026-13-02.sqlite")); + Assert.IsNull(DailyBackup.TryParseDay("febe.sqlite")); + Assert.IsNull(DailyBackup.TryParseDay("altro-2026-01-02.sqlite")); + Assert.IsNull(DailyBackup.TryParseDay("febe-2026-01-02.sqlite.part")); + } + + [TestMethod] + public async Task TheDatabaseRefusesToOverwriteACopy() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var target = temp.Combine("copia.sqlite"); + await db.Maintenance.BackupToAsync(target); + await Assert.ThrowsExactlyAsync(() => db.Maintenance.BackupToAsync(target)); + Assert.IsTrue(await db.Maintenance.CheckIntegrityAsync()); + await db.Maintenance.OptimizeAsync(); + } + + private static class LibraryTimes + { + public static DateTimeOffset Noon(DateOnly day) => Core.Domain.LocalCalendar.FromLocal(day.ToDateTime(new TimeOnly(12, 0)), TestZones.Rome); + } +} diff --git a/tests/Febe.Tests/Library/DataFolderCheckTests.cs b/tests/Febe.Tests/Library/DataFolderCheckTests.cs new file mode 100644 index 0000000..8d112fd --- /dev/null +++ b/tests/Febe.Tests/Library/DataFolderCheckTests.cs @@ -0,0 +1,137 @@ +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Library; + +[TestClass] +public sealed class DataFolderCheckTests +{ + private const string Mounts = """ + sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0 + proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0 + /dev/sda1 / ext4 rw,relatime 0 0 + overlay /var/lib/docker/overlay2/x/merged overlay rw,relatime 0 0 + shfs /mnt/user fuse.shfs rw,nosuid,nodev,noatime 0 0 + //nas/foto /mnt/nas cifs rw,relatime,vers=3.1.1 0 0 + nas:/export/dati /dati nfs4 rw,relatime,vers=4.2 0 0 + alberto@server:/home /mnt/remoto fuse.sshfs rw,nosuid,nodev 0 0 + C:\134 /mnt/c 9p rw,noatime,dirsync,aname=drvfs 0 0 + /dev/sdb1 /mnt/disco\040esterno ext4 rw,relatime 0 0 + tmpfs /tmp tmpfs rw,nosuid,nodev 0 0 + /dev/sdc1 /dati/locale xfs rw 0 0 + """; + + [TestMethod] + public void ParsesProcMountsWithEscapes() + { + var entries = MountTable.Parse(Mounts); + Assert.HasCount(12, entries); + Assert.Contains(new MountEntry("/dev/sdb1", "/mnt/disco esterno", "ext4"), entries); + Assert.Contains(new MountEntry("C:\\", "/mnt/c", "9p"), entries); + Assert.AreEqual("a\tb\nc\\d", MountTable.Unescape("a\\011b\\012c\\134d")); + Assert.AreEqual("\\09x", MountTable.Unescape("\\09x"), "Non è una sequenza ottale: resta com'è."); + Assert.IsEmpty(MountTable.Parse("due campi\n\n# commento")); + } + + [TestMethod] + [DataRow("/dati", "nfs4")] + [DataRow("/dati/febe", "nfs4")] + [DataRow("/mnt/nas/Febe/dati", "cifs")] + [DataRow("/mnt/remoto/x", "fuse.sshfs")] + [DataRow("/mnt/c/Users/Alberto/Febe", "9p")] + public void FindsNetworkMounts(string path, string fileSystem) + { + var mount = MountTable.FindContaining(MountTable.Parse(Mounts), path); + Assert.IsNotNull(mount); + Assert.AreEqual(fileSystem, mount.FileSystemType); + Assert.IsTrue(MountTable.IsNetworkFileSystem(mount.FileSystemType)); + + if (!OperatingSystem.IsWindows()) + { + var problem = new DataFolderCheck(() => Mounts).DetectNetwork(path); + Assert.IsNotNull(problem); + Assert.AreEqual(DataFolderProblemKind.NetworkPath, problem.Kind); + Assert.AreEqual(fileSystem, problem.FileSystem); + Assert.AreEqual("La cartella dei dati è su un disco di rete", problem.Title); + Assert.Contains("il motore non è partito", problem.Explanation); + Assert.IsFalse(string.IsNullOrWhiteSpace(problem.Remedy)); + } + } + + [TestMethod] + [DataRow("/dati/locale/febe", "xfs")] + [DataRow("/mnt/user/appdata/febe", "fuse.shfs")] + [DataRow("/var/lib/docker/overlay2/x/merged/dati", "overlay")] + [DataRow("/home/alberto/febe", "ext4")] + [DataRow("/tmp/febe", "tmpfs")] + [DataRow("/datiextra", "ext4")] + [DataRow("/mnt/disco esterno/febe", "ext4")] + public void LocalMountsAreFine(string path, string fileSystem) + { + var mount = MountTable.FindContaining(MountTable.Parse(Mounts), path); + Assert.AreEqual(fileSystem, mount?.FileSystemType); + Assert.IsFalse(MountTable.IsNetworkFileSystem(fileSystem)); + if (!OperatingSystem.IsWindows()) + { + Assert.IsNull(new DataFolderCheck(() => Mounts).DetectNetwork(path)); + } + } + + [TestMethod] + [DataRow(@"\\nas\febe\dati", true)] + [DataRow(@"\\?\UNC\nas\febe", true)] + [DataRow(@"\\.\UNC\nas\febe", true)] + [DataRow(@"\\?\C:\Febe", false)] + [DataRow(@"\\.\C:\Febe", false)] + [DataRow(@"C:\Users\Alberto\AppData\Local\Febe", false)] + [DataRow("/dati", false)] + public void RecognizesUncPaths(string path, bool expected) + { + Assert.AreEqual(expected, DataFolderCheck.IsUncPath(path)); + } + + [TestMethod] + public void UncPathsAreAlwaysNetworkProblems() + { + var problem = new DataFolderCheck(() => null).DetectNetwork(@"\\nas\febe\dati"); + Assert.AreEqual(DataFolderProblemKind.NetworkPath, problem?.Kind); + } + + [TestMethod] + public void ALocalWritableFolderPassesAndIsCreated() + { + using var temp = new TempFolder(); + var path = temp.Combine("dati", "nuova"); + Assert.IsNull(new DataFolderCheck(() => "/dev/sda1 / ext4 rw 0 0").Check(path)); + Assert.IsTrue(Directory.Exists(path)); + Assert.IsEmpty(Directory.GetFiles(path), "La prova di scrittura non lascia file."); + } + + [TestMethod] + public void AFileOrAnImpossibleFolderIsReported() + { + using var temp = new TempFolder(); + var file = temp.Combine("un-file"); + File.WriteAllText(file, "x"); + var check = new DataFolderCheck(() => null); + + Assert.AreEqual(DataFolderProblemKind.NotAFolder, check.Check(file)?.Kind); + var below = check.Check(Path.Combine(file, "dati")); + Assert.AreEqual(DataFolderProblemKind.CannotCreate, below?.Kind); + Assert.Contains("Febe non riesce a creare", below!.Title); + } + + [TestMethod] + public void AFolderThatCannotBeWrittenIsReported() + { + if (!OperatingSystem.IsLinux() || !Directory.Exists("/proc/self")) + { + Assert.Inconclusive("Serve /proc di Linux: una cartella in cui nemmeno root può scrivere."); + } + + var problem = new DataFolderCheck(() => null).Check("/proc/self"); + Assert.AreEqual(DataFolderProblemKind.NotWritable, problem?.Kind); + Assert.AreEqual("Febe non può scrivere nella cartella dei dati", problem!.Title); + Assert.Contains("PUID", problem.Remedy); + } +} diff --git a/tests/Febe.Tests/Library/LibraryDeletionTests.cs b/tests/Febe.Tests/Library/LibraryDeletionTests.cs new file mode 100644 index 0000000..9f5e0e5 --- /dev/null +++ b/tests/Febe.Tests/Library/LibraryDeletionTests.cs @@ -0,0 +1,102 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Library; + +[TestClass] +public sealed class LibraryDeletionTests +{ + [TestMethod] + public async Task ADeletedEntryLosesItsFilesButStaysKnown() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var entry = await library.SaveAsync(account, Make.Entry(account.Id, "777", Make.T0, caption: "Da eliminare"), [TestFile.Photo(1, 1), TestFile.Video(2)]); + var paths = entry.Media.Select(m => library.Layout.FullPath(account, m.RelativePath!)).ToList(); + var sha = entry.Media[0].Sha256!; + Assert.IsTrue(paths.All(File.Exists)); + + library.Clock.Now = Make.T0.AddDays(2); + var deletion = new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock, library.Thumbnails, library.Index); + var result = await deletion.DeleteAsync(entry.Entry.Id); + + Assert.IsTrue(result.Complete); + Assert.HasCount(2, result.DeletedFiles); + Assert.IsFalse(paths.Any(File.Exists)); + Assert.IsFalse(library.Thumbnails.Exists(sha)); + Assert.AreEqual(0, library.Index.Count); + + // It does not come back: the identifier stays known (spec §4.6). + Assert.IsTrue(await library.Db.Entries.IsKnownAsync(account.Id, EntryKind.Post, "777")); + var stored = (await library.Db.Entries.GetWithMediaAsync(entry.Entry.Id))!; + Assert.AreEqual(EntryState.Deleted, stored.Entry.State); + Assert.AreEqual(Make.T0.AddDays(2), stored.Entry.DeletedAt); + Assert.IsEmpty(stored.Media.Where(m => m.State != MediaState.Deleted)); + Assert.IsEmpty((await library.Db.Entries.QueryLibraryAsync(new Core.Storage.LibraryQuery())).Tiles); + + var journal = await AccountJournal.ReadAsync(library.Layout.AccountFolder(account)); + var line = journal.Lines[^1]; + Assert.AreEqual(JournalOps.Delete, line.Op); + Assert.IsTrue(line.Remember); + Assert.HasCount(2, line.Files!); + } + + [TestMethod] + public async Task LetItComeBackRemovesTheRecord() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var entry = await library.SaveAsync(account, Make.Entry(account.Id, "778", Make.T0), [TestFile.Photo(1, 2)]); + + var deletion = new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock, library.Thumbnails, library.Index); + var result = await deletion.DeleteAsync(entry.Entry.Id, DeletionMode.AllowReturn); + + Assert.IsTrue(result.Complete); + Assert.IsNull(await library.Db.Entries.GetAsync(entry.Entry.Id)); + Assert.IsFalse(await library.Db.Entries.IsKnownAsync(account.Id, EntryKind.Post, "778")); + var line = (await AccountJournal.ReadAsync(library.Layout.AccountFolder(account))).Lines[^1]; + Assert.IsFalse(line.Remember); + } + + [TestMethod] + public async Task OnlyTheChosenEntryIsTouched() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var luca = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200")); + var bytes = TestFile.PhotoBytes(3); + var mine = await library.SaveAsync(marta, Make.Entry(marta.Id, "1", Make.T0), [new TestFile(Make.Photo(1), bytes, ".jpg")]); + var theirs = await library.SaveAsync(luca, Make.Entry(luca.Id, "1", Make.T0, EntryKind.Tagged), [new TestFile(Make.Photo(1), bytes, ".jpg")]); + var neighbour = await library.SaveAsync(marta, Make.Entry(marta.Id, "2", Make.T0), [TestFile.Photo(1, 4)]); + + var deletion = new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock, library.Thumbnails, library.Index); + await deletion.DeleteAsync(mine.Entry.Id); + + Assert.IsTrue(File.Exists(library.Layout.FullPath(luca, theirs.Media[0].RelativePath!))); + Assert.IsTrue(File.Exists(library.Layout.FullPath(marta, neighbour.Media[0].RelativePath!))); + Assert.IsTrue(library.Thumbnails.Exists(theirs.Media[0].Sha256!), "La miniatura serve ancora all'altro account."); + Assert.AreEqual(EntryState.Downloaded, (await library.Db.Entries.GetAsync(theirs.Entry.Id))!.State); + } + + [TestMethod] + public async Task MissingFilesAndUnknownEntriesAreReported() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var entry = await library.SaveAsync(account, Make.Entry(account.Id, "9", Make.T0), [TestFile.Photo(1, 5), TestFile.Photo(2, 6)]); + File.Delete(library.Layout.FullPath(account, entry.Media[1].RelativePath!)); + + var deletion = new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock); + var results = await deletion.DeleteManyAsync([entry.Entry.Id, 424242]); + + Assert.HasCount(1, results[0].DeletedFiles); + Assert.HasCount(1, results[0].MissingFiles); + Assert.IsTrue(results[0].Complete); + Assert.IsFalse(results[1].Found); + } +} diff --git a/tests/Febe.Tests/Library/LibraryIngestTests.cs b/tests/Febe.Tests/Library/LibraryIngestTests.cs new file mode 100644 index 0000000..e94a49f --- /dev/null +++ b/tests/Febe.Tests/Library/LibraryIngestTests.cs @@ -0,0 +1,120 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Library; + +[TestClass] +public sealed class LibraryIngestTests +{ + [TestMethod] + public async Task StoresFilesWithSchemeHashesThumbnailsAndJournal() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + // 16:22:05 UTC on 10 October is 18:22:05 in Rome. + var entry = Make.Entry(account.Id, "321", new DateTimeOffset(2026, 10, 10, 16, 22, 5, TimeSpan.Zero), caption: "Tramonto") with { Code = "DBx3kQ2" }; + var saved = await library.SaveAsync(account, entry, [TestFile.Photo(1, 11), TestFile.Photo(2, 12, 1350, 1080), TestFile.Video(3)]); + + Assert.AreEqual(EntryState.Downloaded, saved.Entry.State); + Assert.AreEqual("post/2026/2026-10-10_18-22-05_DBx3kQ2_1.jpg", saved.Media[0].RelativePath); + Assert.AreEqual("post/2026/2026-10-10_18-22-05_DBx3kQ2_2.jpg", saved.Media[1].RelativePath); + Assert.AreEqual("post/2026/2026-10-10_18-22-05_DBx3kQ2_3.mp4", saved.Media[2].RelativePath); + + var photoPath = library.Layout.FullPath(account, saved.Media[0].RelativePath!); + Assert.AreEqual(entry.PublishedAt.UtcDateTime, File.GetLastWriteTimeUtc(photoPath), "La data del file è quella di pubblicazione."); + Assert.IsNotNull(saved.Media[0].PerceptualHash); + Assert.IsNull(saved.Media[2].PerceptualHash, "I video non hanno impronta visiva."); + Assert.AreEqual(1350, saved.Media[1].Width); + Assert.AreEqual(1080, saved.Media[1].Height); + Assert.IsTrue(saved.Media[0].HasThumbnail); + Assert.IsTrue(library.Thumbnails.Exists(saved.Media[0].Sha256!)); + Assert.IsFalse(saved.Media[2].HasThumbnail, "Un video senza copertina mostra la tessera neutra."); + Assert.AreEqual(2, library.Index.Count); + + var journal = await AccountJournal.ReadAsync(library.Layout.AccountFolder(account)); + var line = journal.Lines.Single(); + Assert.AreEqual(3, line.Files!.Count); + Assert.AreEqual(saved.Media[2].Sha256, line.Files[2].Sha256); + } + + [TestMethod] + public async Task VideoCoversBecomeThumbnailsAndHighlightsUseTheirScheme() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var entry = Make.Entry(account.Id, "3391207", new DateTimeOffset(2025, 8, 2, 8, 11, 12, TimeSpan.Zero), EntryKind.Highlight); + var added = await library.Db.Entries.AddAsync(entry, [Make.Video()]); + var cover = new MemoryStream(TestFile.PhotoBytes(5, 1080, 1920)); + + var result = await library.Ingest.SaveMediaAsync(account, added.Stored.Entry, added.Stored.Media[0], new MediaContent { Content = new MemoryStream(new byte[] { 1, 2, 3 }), Extension = "mp4", Cover = cover }, "Estate 2025"); + + Assert.AreEqual(MediaSaveOutcome.Stored, result.Outcome); + Assert.AreEqual("evidenza/Estate 2025/2025-08-02_10-11-12_3391207_1.mp4", result.File!.RelativePath); + Assert.IsTrue(result.File.HasThumbnail); + Assert.IsTrue(cover.CanRead, "Lo stream della copertina resta a chi lo ha passato."); + } + + [TestMethod] + public async Task AnIdenticalFileInTheSameAccountIsDiscarded() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var bytes = TestFile.PhotoBytes(21); + var imported = await library.SaveAsync(account, Make.Entry(account.Id, "x", Make.T0) with { InstagramId = null, Provenance = Provenance.Imported }, [new TestFile(Make.Photo(1), bytes, ".jpg")]); + Assert.AreEqual(EntryState.Imported, imported.Entry.State); + + var downloaded = await library.Db.Entries.AddAsync(Make.Entry(account.Id, "555", Make.T0), [Make.Photo()]); + var result = await library.Ingest.SaveMediaAsync(account, downloaded.Stored.Entry, downloaded.Stored.Media[0], new MediaContent { Content = new MemoryStream(bytes), Extension = ".jpg" }); + + Assert.AreEqual(MediaSaveOutcome.IdenticalInAccount, result.Outcome); + Assert.AreEqual(imported.Media[0].Id, result.Identical!.Media.Id); + Assert.HasCount(1, Directory.GetFiles(library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories)); + Assert.AreEqual(MediaState.ToDownload, (await library.Db.Media.GetAsync(downloaded.Stored.Media[0].Id))!.State); + + // The same bytes in another account are a separate copy (spec §8.3). + var other = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200")); + var tagged = await library.SaveAsync(other, Make.Entry(other.Id, "555", Make.T0, EntryKind.Tagged), [new TestFile(Make.Photo(1), bytes, ".jpg")]); + Assert.AreEqual(EntryState.Downloaded, tagged.Entry.State); + } + + [TestMethod] + public async Task ASimilarPhotoIsKeptAndPairedForAlberto() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + using var scene = TestImages.Scene(31, 1200, 900); + var original = await library.SaveAsync(account, Make.Entry(account.Id, "1", Make.T0), [new TestFile(Make.Photo(1), TestImages.Jpeg(scene, 92), ".jpg")]); + using var smaller = TestImages.Resize(scene, 600, 450); + var copy = await library.SaveAsync(account, Make.Entry(account.Id, "2", Make.T0.AddDays(1)), [new TestFile(Make.Photo(1), TestImages.Jpeg(smaller, 60), ".jpg")]); + + Assert.AreEqual(EntryState.Downloaded, copy.Entry.State, "Restano entrambi: nessuna sostituzione automatica."); + var pair = (await library.Db.Duplicates.ListPendingAsync()).Single(); + Assert.AreEqual(original.Media[0].Id, pair.ExistingMediaId); + Assert.AreEqual(copy.Media[0].Id, pair.CandidateMediaId); + Assert.AreEqual(DuplicateReason.VisuallySimilar, pair.Reason); + Assert.IsTrue(File.Exists(library.Layout.FullPath(account, original.Media[0].RelativePath!))); + Assert.IsTrue(File.Exists(library.Layout.FullPath(account, copy.Media[0].RelativePath!))); + } + + [TestMethod] + public async Task ProfilePicturesAreNamedAfterTheirHashAndTooLargeVideosSkipped() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var bytes = TestFile.PhotoBytes(40, 320, 320); + var saved = await library.SaveAsync(account, Make.Entry(account.Id, "pp1", Make.T0, EntryKind.ProfilePicture), [new TestFile(Make.Photo(1), bytes, ".jpg")]); + var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)); + Assert.AreEqual($"profilo/2026/2026-10-13_10-00-00_{sha[..8]}_1.jpg", saved.Media[0].RelativePath); + + var video = await library.Db.Entries.AddAsync(Make.Entry(account.Id, "big", Make.T0), [Make.Video()]); + await Assert.ThrowsExactlyAsync(() => library.Ingest.SaveMediaAsync( + account, video.Stored.Entry, video.Stored.Media[0], new MediaContent { Content = new MemoryStream(new byte[10_000]), Extension = ".mp4", MaxBytes = 1000 })); + Assert.IsEmpty(Directory.GetFiles(library.Layout.AccountFolder(account), "*.mp4", SearchOption.AllDirectories)); + } +} diff --git a/tests/Febe.Tests/Library/LibraryRebuildTests.cs b/tests/Febe.Tests/Library/LibraryRebuildTests.cs new file mode 100644 index 0000000..8f67533 --- /dev/null +++ b/tests/Febe.Tests/Library/LibraryRebuildTests.cs @@ -0,0 +1,175 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Tests.Support; + +namespace Febe.Tests.Library; + +[TestClass] +public sealed class LibraryRebuildTests +{ + /// + /// «Fatto quando» of M1: the database is rebuilt from a test library after it was lost, without downloading + /// anything again, honouring deletions. + /// + [TestMethod] + public async Task TheDatabaseIsRebuiltFromTheLibraryAfterItIsLost() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var outsideFolder = temp.Combine("altro-disco", "luca"); + var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100") with { DisplayName = "Marta B.", IsFollowed = true }); + var luca = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200") with { Folder = outsideFolder }); + var me = await library.Db.Accounts.AddAsync(Make.Account("tuo.profilo", "300", mine: true)); + + var post = await library.SaveAsync(marta, Make.Entry(marta.Id, "p1", Make.T0.AddDays(-10), caption: "Però che vista") with { Code = "AbC1" }, [TestFile.Photo(1, 1), TestFile.Photo(2, 2), TestFile.Video(3)]); + var story = await library.SaveAsync(marta, Make.Entry(marta.Id, "s1", Make.T0.AddHours(-3), EntryKind.Story) with { ExpiresAt = Make.T0.AddHours(21) }, [TestFile.Video(1)]); + var collection = await library.Db.Highlights.UpsertAsync(new Highlight { AccountId = marta.Id, InstagramId = "h1", Title = "Estate 2025", Position = 2, DiscoveredAt = Make.T0 }); + var highlightEntry = await library.Db.Entries.AddAsync(Make.Entry(marta.Id, "e1", Make.T0.AddDays(-60), EntryKind.Highlight), [Make.Photo()]); + await library.Db.Highlights.AddItemAsync(collection.Id, highlightEntry.Stored.Entry.Id); + await library.Ingest.SaveMediaAsync(marta, highlightEntry.Stored.Entry, highlightEntry.Stored.Media[0], new MediaContent { Content = new MemoryStream(TestFile.PhotoBytes(3)), Extension = ".jpg" }, collection.Title); + await library.Ingest.AppendJournalAsync(highlightEntry.Stored.Entry.Id); + var forgotten = await library.SaveAsync(marta, Make.Entry(marta.Id, "gone", Make.T0.AddDays(-5)), [TestFile.Photo(1, 4)]); + var comesBack = await library.SaveAsync(marta, Make.Entry(marta.Id, "back", Make.T0.AddDays(-6)), [TestFile.Photo(1, 5)]); + var broken = await library.SaveAsync(marta, Make.Entry(marta.Id, "broken", Make.T0.AddDays(-7)), [TestFile.Photo(1, 6), TestFile.Photo(2, 7)]); + var imported = await library.SaveAsync(marta, Make.Entry(marta.Id, "imp", Make.T0.AddDays(-400)) with { InstagramId = null, Code = null, Provenance = Provenance.Imported }, [TestFile.Photo(1, 8)]); + + var lucaPost = await library.SaveAsync(luca, Make.Entry(luca.Id, "l1", Make.T0.AddDays(-1)), [TestFile.Photo(1, 9)]); + var tagged = await library.SaveAsync(me, Make.Entry(me.Id, "p1", Make.T0.AddDays(-10), EntryKind.Tagged) with { AuthorUsername = "marta.demo" }, [TestFile.Photo(1, 1)]); + + var deletion = new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock, library.Thumbnails, library.Index); + await deletion.DeleteAsync(forgotten.Entry.Id, DeletionMode.Remember); + await deletion.DeleteAsync(comesBack.Entry.Id, DeletionMode.AllowReturn); + File.Delete(library.Layout.FullPath(marta, broken.Media[1].RelativePath!)); + await File.WriteAllTextAsync(Path.Combine(library.Layout.AccountFolder(marta), "post", "aggiunto-a-mano.jpg"), "x"); + Directory.CreateDirectory(Path.Combine(library.Layout.Root, "cartella-senza-registro")); + await File.WriteAllTextAsync(Path.Combine(library.Layout.Root, "cartella-senza-registro", "foto.jpg"), "x"); + + var before = await Snapshot(library); + var filesBefore = Directory.GetFiles(temp.Path, "*", SearchOption.AllDirectories).Where(f => !f.StartsWith(library.Data.Root, StringComparison.Ordinal)).Order().ToList(); + + await library.LoseDatabaseAsync(); + Assert.IsEmpty(await library.Db.Accounts.ListAsync()); + + var index = new PerceptualHashIndex(); + var rebuilder = new LibraryRebuilder(library.Db, library.Layout, library.Clock, library.Thumbnails, null, index); + var progress = new List(); + var report = await rebuilder.RebuildAsync(new RebuildOptions { ExtraAccountFolders = [outsideFolder] }, new SyncProgress(progress.Add)); + + Assert.AreEqual(3, report.AccountFolders); + Assert.AreEqual(3, report.AccountsCreated); + CollectionAssert.AreEqual(new[] { "cartella-senza-registro" }, report.FoldersWithoutJournal.ToArray()); + Assert.AreEqual(1, report.FilesMissing); + Assert.AreEqual(1, report.UntrackedFiles); + Assert.AreEqual(1, report.EntriesDeleted); + Assert.AreEqual(0, report.HashMismatches); + Assert.AreEqual(0, report.InvalidLines); + + var after = await Snapshot(library); + foreach (var (key, expected) in before) + { + if (key.StartsWith("marta.demo|Post|broken", StringComparison.Ordinal)) + { + continue; + } + + Assert.IsTrue(after.TryGetValue(key, out var actual), $"Manca dopo la ricostruzione: {key}"); + Assert.AreEqual(expected, actual, key); + } + + Assert.IsFalse(after.Keys.Any(k => k.Contains("|back", StringComparison.Ordinal)), "«Lascia che torni» non ricompare."); + Assert.IsTrue(await library.Db.Entries.IsKnownAsync((await library.Db.Accounts.FindByInstagramIdAsync("100"))!.Id, EntryKind.Post, "gone")); + + // Accounts come back paused, with their identity and folders. + var accounts = await library.Db.Accounts.ListAsync(); + Assert.IsTrue(accounts.All(a => a.State == AccountState.Paused)); + var martaAgain = accounts.Single(a => a.InstagramId == "100"); + Assert.AreEqual("Marta B.", martaAgain.DisplayName); + Assert.IsNull(martaAgain.Folder); + Assert.AreEqual(outsideFolder, accounts.Single(a => a.InstagramId == "200").Folder); + Assert.IsTrue(accounts.Single(a => a.InstagramId == "300").IsMine); + + // The file that disappeared is reported, not downloaded again. + var brokenAgain = (await library.Db.Entries.FindAsync(martaAgain.Id, EntryKind.Post, "broken"))!; + Assert.AreEqual(EntryState.Partial, brokenAgain.State); + + // Highlights, thumbnails and perceptual hashes are back. + var collections = await library.Db.Highlights.ListAsync(martaAgain.Id); + Assert.AreEqual("Estate 2025", collections.Single().Title); + Assert.HasCount(1, await library.Db.Highlights.ListItemsAsync(collections.Single().Id)); + Assert.IsTrue(library.Thumbnails.Exists(post.Media[0].Sha256!)); + Assert.AreEqual(7, index.Count, "Impronte delle foto presenti: due del post, evidenza, foto rimasta, importata, luca, taggato."); + Assert.HasCount(7, await library.Db.Media.LoadPerceptualHashesAsync()); + + // Nothing on disk changed. + var filesAfter = Directory.GetFiles(temp.Path, "*", SearchOption.AllDirectories).Where(f => !f.StartsWith(library.Data.Root, StringComparison.Ordinal)).Order().ToList(); + CollectionAssert.AreEqual(filesBefore, filesAfter); + Assert.IsNotEmpty(progress); + + // A second run adds nothing. + var again = await rebuilder.RebuildAsync(new RebuildOptions { ExtraAccountFolders = [outsideFolder] }); + Assert.AreEqual(0, again.EntriesCreated); + Assert.AreEqual(0, again.AccountsCreated); + Assert.AreEqual(report.EntriesCreated, again.EntriesAlreadyPresent); + CollectionAssert.AreEquivalent(after.ToList(), (await Snapshot(library)).ToList()); + + _ = (story, imported, lucaPost, tagged); + } + + [TestMethod] + public async Task ADeletedEntryThatCameBackIsRestored() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var entry = await library.SaveAsync(marta, Make.Entry(marta.Id, "x", Make.T0), [TestFile.Photo(1, 1)]); + await new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock).DeleteAsync(entry.Entry.Id, DeletionMode.AllowReturn); + var again = await library.SaveAsync(marta, Make.Entry(marta.Id, "x", Make.T0), [TestFile.Photo(1, 1)]); + + await library.LoseDatabaseAsync(); + var report = await new LibraryRebuilder(library.Db, library.Layout, library.Clock).RebuildAsync(); + + Assert.AreEqual(1, report.EntriesCreated); + var restored = (await library.Db.Entries.FindAsync((await library.Db.Accounts.FindByInstagramIdAsync("100"))!.Id, EntryKind.Post, "x"))!; + Assert.AreEqual(EntryState.Downloaded, restored.State); + Assert.AreEqual(again.Media[0].RelativePath, (await library.Db.Media.ListByEntryAsync(restored.Id))[0].RelativePath); + } + + [TestMethod] + public async Task AnEmptyLibraryRebuildsNothing() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var report = await new LibraryRebuilder(library.Db, library.Layout, library.Clock).RebuildAsync(); + Assert.AreEqual(0, report.AccountFolders); + Assert.AreEqual(0, report.EntriesCreated); + } + + private sealed class SyncProgress(Action report) : IProgress + { + public void Report(T value) => report(value); + } + + /// Everything that identifies the library content, keyed by account and entry identity. + private static async Task> Snapshot(TestLibrary library) + { + var result = new Dictionary(StringComparer.Ordinal); + foreach (var account in await library.Db.Accounts.ListAsync()) + { + var entries = await library.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Limit = 1000 }); + foreach (var entry in entries) + { + var media = await library.Db.Media.ListByEntryAsync(entry.Id); + var id = entry.InstagramId ?? $"t{entry.PublishedAt.ToUnixTimeMilliseconds()}"; + result[$"{account.Username}|{entry.Kind}|{id}"] = $"{entry.State}|{entry.Code}|{entry.Caption}|{entry.PublishedAt:O}|{entry.Provenance}|{entry.AuthorUsername}"; + foreach (var m in media) + { + result[$"{account.Username}|{entry.Kind}|{id}|{m.Position}|{m.Kind}|"] = + $"{m.State}|{m.RelativePath}|{m.Sha256}|{m.PerceptualHash}|{m.Bytes}|{m.HasThumbnail}|{m.Width}x{m.Height}"; + } + } + } + + return result; + } +} diff --git a/tests/Febe.Tests/Library/NamingSchemeTests.cs b/tests/Febe.Tests/Library/NamingSchemeTests.cs new file mode 100644 index 0000000..ed97e94 --- /dev/null +++ b/tests/Febe.Tests/Library/NamingSchemeTests.cs @@ -0,0 +1,166 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Library; + +[TestClass] +public sealed class NamingSchemeTests +{ + private static readonly TimeZoneInfo Rome = TestZones.Rome; + + /// A local time in Rome as an instant. + private static DateTimeOffset RomeTime(int y, int mo, int d, int h, int mi, int s) => LocalCalendar.FromLocal(new DateTime(y, mo, d, h, mi, s), Rome); + + [TestMethod] + public void DefaultSchemesProduceTheExamplesOfTheSpecification() + { + // Spec §4.7: marta.demo\post\2026\2026-10-10_18-22-05_DBx3kQ2_2.jpg (the account folder is the root). + var post = NamingScheme.General.RenderRelativePath(new NamingValues("marta.demo", EntryKind.Post, RomeTime(2026, 10, 10, 18, 22, 5), "DBx3kQ2", 2, ".jpg"), Rome); + Assert.AreEqual("post/2026/2026-10-10_18-22-05_DBx3kQ2_2.jpg", post); + + var story = NamingScheme.General.RenderRelativePath(new NamingValues("marta.demo", EntryKind.Story, RomeTime(2026, 10, 13, 9, 41, 7), "3742118", 1, "mp4"), Rome); + Assert.AreEqual("storie/2026/2026-10-13_09-41-07_3742118_1.mp4", story); + + var highlight = NamingScheme.Highlight.RenderRelativePath(new NamingValues("marta.demo", EntryKind.Highlight, RomeTime(2025, 8, 2, 10, 11, 12), "3391207", 1, ".JPG", "Estate 2025"), Rome); + Assert.AreEqual("evidenza/Estate 2025/2025-08-02_10-11-12_3391207_1.jpg", highlight); + } + + [TestMethod] + public void DatesAndTimesAreInAlbertosZone() + { + // 22:30 UTC on 31 December 2025 is already 2026 in Rome (CET, +1): year folder and date follow the local time. + var instant = new DateTimeOffset(2025, 12, 31, 23, 30, 0, TimeSpan.Zero); + var path = NamingScheme.General.RenderRelativePath(new NamingValues("a", EntryKind.Post, instant, "X", 1, ".jpg"), Rome); + Assert.AreEqual("post/2026/2026-01-01_00-30-00_X_1.jpg", path); + + // Summer time: +2. + var summer = new DateTimeOffset(2026, 7, 1, 10, 0, 0, TimeSpan.Zero); + Assert.AreEqual("post/2026/2026-07-01_12-00-00_X_1.jpg", NamingScheme.General.RenderRelativePath(new NamingValues("a", EntryKind.Post, summer, "X", 1, ".jpg"), Rome)); + + // Same instant, UTC zone. + Assert.AreEqual("post/2026/2026-07-01_10-00-00_X_1.jpg", NamingScheme.General.RenderRelativePath(new NamingValues("a", EntryKind.Post, summer, "X", 1, ".jpg"), TimeZoneInfo.Utc)); + } + + [TestMethod] + public void BackslashAndSlashSeparateFoldersOnEveryPlatform() + { + var values = new NamingValues("marta.demo", EntryKind.Tagged, RomeTime(2026, 3, 4, 5, 6, 7), "Cd3", 1, ".jpg"); + var backslash = NamingScheme.Parse(@"{account}\{tipo}\{anno}-{mese}\{data}_{codice}", false); + var slash = NamingScheme.Parse("{account}/{tipo}/{anno}-{mese}/{data}_{codice}", false); + Assert.AreEqual("taggati/2026-03/2026-03-04_Cd3.jpg", backslash.RenderRelativePath(values, Rome)); + Assert.AreEqual(backslash.RenderRelativePath(values, Rome), slash.RenderRelativePath(values, Rome)); + Assert.HasCount(3, backslash.Render(values, Rome)); + } + + [TestMethod] + public void SchemesWithoutTheAccountSegmentAreRelativeToTheAccountFolder() + { + var values = new NamingValues("marta.demo", EntryKind.Post, RomeTime(2026, 3, 4, 5, 6, 7), "Cd3", 2, ".jpg"); + Assert.AreEqual("2026/marta.demo_Cd3_2.jpg", NamingScheme.Parse("{anno}/{account}_{codice}_{n}", false).RenderRelativePath(values, Rome)); + } + + [TestMethod] + public void PlaceholderValuesAreSanitized() + { + var values = new NamingValues("marta.demo", EntryKind.Highlight, RomeTime(2026, 3, 4, 5, 6, 7), "1", 1, ".jpg", "Ore 10:30 / sera?"); + Assert.AreEqual("evidenza/Ore 10_30 _ sera_/2026-03-04_05-06-07_1_1.jpg", NamingScheme.Highlight.RenderRelativePath(values, Rome)); + + var reserved = new NamingValues("con", EntryKind.Highlight, RomeTime(2026, 3, 4, 5, 6, 7), "1", 1, ".jpg", "NUL"); + var scheme = NamingScheme.Parse(@"{raccolta}\{account}", forHighlights: true); + Assert.AreEqual("NUL_/con_.jpg", scheme.RenderRelativePath(reserved, Rome)); + + var empty = values with { Collection = " " }; + Assert.AreEqual("evidenza/senza titolo/2026-03-04_05-06-07_1_1.jpg", NamingScheme.Highlight.RenderRelativePath(empty, Rome)); + } + + [TestMethod] + [DataRow("", "vuoto")] + [DataRow("{account}\\{tipo}\\", "manca il nome")] + [DataRow("{account}\\\\{tipo}", "due barre")] + [DataRow("{account}\\{foto}", "Segnaposto sconosciuto: {foto}")] + [DataRow("{account}\\{tipo", "non è chiusa")] + [DataRow("{account}\\tipo}", "non ha la sua apertura")] + [DataRow("{account}\\{}", "vuoto")] + [DataRow("{account}\\{raccolta}\\{n}", "solo nello schema per le raccolte")] + public void InvalidSchemesAreExplained(string text, string message) + { + var validation = NamingScheme.Validate(text, forHighlights: false); + Assert.IsFalse(validation.IsValid); + Assert.IsTrue(validation.Errors.Any(e => e.Contains(message, StringComparison.Ordinal)), string.Join(" | ", validation.Errors)); + Assert.ThrowsExactly(() => NamingScheme.Parse(text, false)); + } + + [TestMethod] + public void RiskySchemesGetWarnings() + { + Assert.IsEmpty(NamingScheme.Validate(NamingScheme.DefaultGeneral, false).Warnings); + Assert.IsEmpty(NamingScheme.Validate(NamingScheme.DefaultHighlight, true).Warnings); + Assert.IsNotEmpty(NamingScheme.Validate(@"{account}\{data}", false).Warnings); + Assert.IsNotEmpty(NamingScheme.Validate(@"{account}\{data}_{codice}", false).Warnings); + Assert.IsNotEmpty(NamingScheme.Validate(@"{account}\evidenza\{codice}_{n}", true).Warnings); + Assert.IsTrue(NamingScheme.Validate(@"{Account}\{TIPO}\{n}", false).IsValid, "I segnaposto non distinguono maiuscole."); + } + + [TestMethod] + public void CodeDependsOnTheKind() + { + var post = new Entry { AccountId = 1, Kind = EntryKind.Post, InstagramId = "321", Code = "DBx3kQ2", PublishedAt = Make.T0, DiscoveredAt = Make.T0 }; + Assert.AreEqual("DBx3kQ2", post.NameCode()); + Assert.AreEqual("321", (post with { Kind = EntryKind.Story }).NameCode()); + Assert.AreEqual("abcdef01", (post with { Kind = EntryKind.ProfilePicture }).NameCode("abcdef0123456789")); + Assert.AreEqual("DBx3kQ2", (post with { Kind = EntryKind.Tagged }).NameCode()); + + var values = NamingValues.For("marta.demo", post with { Kind = EntryKind.ProfilePicture }, 1, ".jpg", sha256: Make.Sha(0xABCDEF)); + Assert.AreEqual("profilo/2026/2026-10-13_10-00-00_00000000_1.jpg", NamingScheme.General.RenderRelativePath(values, Rome)); + } + + [TestMethod] + public void LayoutResolvesAccountFoldersAndFitsPaths() + { + using var temp = new TempFolder(); + var layout = new LibraryLayout(temp.Combine("libreria")); + var account = Make.Account("marta.demo"); + Assert.AreEqual(Path.Combine(layout.Root, "marta.demo"), layout.AccountFolder(account)); + Assert.AreEqual(Path.Combine(layout.Root, "vecchio.nome"), layout.AccountFolder(account with { Folder = "vecchio.nome" })); + var outside = temp.Combine("altrove", "marta"); + Assert.AreEqual(outside, layout.AccountFolder(account with { Folder = outside })); + + Assert.IsNull(layout.FolderSetting(Path.Combine(layout.Root, "marta.demo"), "marta.demo")); + Assert.AreEqual("vecchio.nome", layout.FolderSetting(Path.Combine(layout.Root, "vecchio.nome"), "marta.demo")); + Assert.AreEqual(outside, layout.FolderSetting(outside, "marta.demo")); + + Assert.ThrowsExactly(() => LibraryLayout.FullPath(layout.AccountFolder(account), "../fuori.jpg")); + var relative = layout.RelativePathFor(layout.AccountFolder(account), NamingScheme.General, new NamingValues("marta.demo", EntryKind.Post, Make.T0, "X", 1, ".jpg"), Rome); + Assert.AreEqual("post/2026/2026-10-13_10-00-00_X_1.jpg", relative); + Assert.AreEqual(Path.Combine(layout.Root, "marta.demo", "post", "2026", "2026-10-13_10-00-00_X_1.jpg"), layout.FullPath(account, relative)); + } + + [TestMethod] + public void PreviewShowsTheTreeOfMockup08() + { + var preview = NamingPreview.Build(NamingScheme.DefaultGeneral, NamingScheme.DefaultHighlight, Rome, "marta.demo"); + Assert.IsTrue(preview.IsValid); + Assert.AreEqual("marta.demo", preview.AccountFolder); + Assert.HasCount(3, preview.Folders); + CollectionAssert.AreEqual(new[] { "post", "2026" }, preview.Folders[0].Path.ToArray()); + Assert.AreEqual(new NamingPreviewFile("2026-10-10_18-22-05_DBx3kQ2_2.jpg", MediaKind.Photo), preview.Folders[0].Files.Single()); + CollectionAssert.AreEqual(new[] { "storie", "2026" }, preview.Folders[1].Path.ToArray()); + Assert.AreEqual(new NamingPreviewFile("2026-10-13_09-41-07_3742118_1.mp4", MediaKind.Video), preview.Folders[1].Files.Single()); + CollectionAssert.AreEqual(new[] { "evidenza", "Estate 2025" }, preview.Folders[2].Path.ToArray()); + Assert.AreEqual("2025-08-02_10-11-12_3391207_1.jpg", preview.Folders[2].Files.Single().Name); + + // The preview reads the same in any zone: sample times are local. + var utc = NamingPreview.Build(NamingScheme.DefaultGeneral, NamingScheme.DefaultHighlight, TimeZoneInfo.Utc, "marta.demo"); + Assert.AreEqual(preview.Folders[0].Files[0], utc.Folders[0].Files[0]); + + var flat = NamingPreview.Build(@"{account}\{data}_{codice}_{n}", @"{account}\{raccolta}\{n}", Rome); + Assert.HasCount(2, flat.Folders); + Assert.HasCount(2, flat.Folders[0].Files); + + var broken = NamingPreview.Build("{account}\\{x}", NamingScheme.DefaultHighlight, Rome); + Assert.IsFalse(broken.IsValid); + Assert.StartsWith("Schema: ", broken.Errors[0]); + Assert.HasCount(1, broken.Folders); + } +} diff --git a/tests/Febe.Tests/Library/PerceptualHashTests.cs b/tests/Febe.Tests/Library/PerceptualHashTests.cs new file mode 100644 index 0000000..8e565fb --- /dev/null +++ b/tests/Febe.Tests/Library/PerceptualHashTests.cs @@ -0,0 +1,187 @@ +using System.Diagnostics; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Tests.Support; +using SkiaSharp; + +namespace Febe.Tests.Library; + +[TestClass] +public sealed class PerceptualHashTests +{ + private const int Scenes = 24; + + public TestContext TestContext { get; set; } = null!; + + private static ulong Hash(byte[] encoded) => PerceptualHash.Compute(new MemoryStream(encoded)) ?? throw new AssertFailedException("Immagine non decodificata."); + + private static ulong Hash(SKBitmap bitmap) => Hash(TestImages.Png(bitmap)); + + /// + /// Calibration of (spec §9.3, §14.1): resized and recompressed + /// variants must be duplicates, cropped variants must not, different scenes must not. + /// + [TestMethod] + public void ResizedAndRecompressedAreDuplicatesCroppedAreNot() + { + var variantMax = 0; + var cropMin = 64; + var originals = new List(); + for (var seed = 1; seed <= Scenes; seed++) + { + var (width, height) = seed % 3 == 0 ? (900, 1200) : (1200, 900); + using var scene = TestImages.Scene(seed, width, height); + var original = Hash(TestImages.Jpeg(scene, 92)); + originals.Add(original); + + var variants = new List<(string Name, ulong Hash)>(); + foreach (var scale in new[] { 0.5, 0.25, 0.08, 1.5 }) + { + using var resized = TestImages.Resize(scene, (int)(width * scale), (int)(height * scale)); + variants.Add(($"ridimensionata {scale:P0}", Hash(TestImages.Jpeg(resized, 90)))); + } + + foreach (var quality in new[] { 95, 70, 40, 20 }) + { + variants.Add(($"ricompressa q{quality}", Hash(TestImages.Jpeg(scene, quality)))); + } + + using (var small = TestImages.Resize(scene, width / 3, height / 3)) + { + // Resized, then recompressed twice: what a re-shared photo looks like. + var twice = TestImages.Jpeg(TestImages.Decode(TestImages.Jpeg(small, 60)), 45); + variants.Add(("ridimensionata e ricompressa", Hash(twice))); + } + + variants.Add(("PNG", Hash(TestImages.Png(scene)))); + + foreach (var (name, hash) in variants) + { + var distance = PerceptualHash.Distance(original, hash); + variantMax = Math.Max(variantMax, distance); + Assert.IsLessThanOrEqualTo(PerceptualHash.DuplicateThreshold, distance, $"Scena {seed}, {name}: distanza {distance}"); + } + + var side = Math.Min(width, height); + var crops = new (string Name, SKRectI Area)[] + { + ("centrale 80%", SKRectI.Create(width / 10, height / 10, width * 8 / 10, height * 8 / 10)), + ("centrale 75%", SKRectI.Create(width / 8, height / 8, width * 3 / 4, height * 3 / 4)), + ("centrale 60%", SKRectI.Create(width / 5, height / 5, width * 3 / 5, height * 3 / 5)), + ("lato sinistro tolto 10%", SKRectI.Create(width / 10, 0, width * 9 / 10, height)), + ("lato sinistro tolto 25%", SKRectI.Create(width / 4, 0, width * 3 / 4, height)), + ("in alto tolto 33%", SKRectI.Create(0, height / 3, width, height * 2 / 3)), + ("quadrato", SKRectI.Create((width - side) / 2, (height - side) / 2, side, side)), + ("quarto in basso a destra", SKRectI.Create(width / 2, height / 2, width / 2, height / 2)), + }; + foreach (var (name, area) in crops) + { + using var cropped = TestImages.Crop(scene, area); + var distance = PerceptualHash.Distance(original, Hash(TestImages.Jpeg(cropped, 90))); + cropMin = Math.Min(cropMin, distance); + Assert.IsGreaterThan(PerceptualHash.DuplicateThreshold, distance, $"Scena {seed}, ritaglio {name}: distanza {distance}"); + } + } + + var distinctMin = 64; + for (var i = 0; i < originals.Count; i++) + { + for (var j = i + 1; j < originals.Count; j++) + { + distinctMin = Math.Min(distinctMin, PerceptualHash.Distance(originals[i], originals[j])); + } + } + + TestContext.WriteLine($"Taratura: varianti fino a {variantMax}, ritagli da {cropMin}, scene diverse da {distinctMin}; soglia {PerceptualHash.DuplicateThreshold}."); + Assert.IsGreaterThan(PerceptualHash.DuplicateThreshold, distinctMin); + } + + [TestMethod] + public void OrientationIsAppliedBeforeHashing() + { + using var scene = TestImages.Scene(7, 1200, 900); + var upright = Hash(TestImages.Jpeg(scene, 92)); + + // A camera stores the pixels sideways and tags orientation 6 («rotate 90° clockwise to display»). + using var stored = TestImages.RotateCounterClockwise(scene); + var tagged = TestImages.WithExifOrientation(TestImages.Jpeg(stored, 92), 6); + var untagged = TestImages.Jpeg(stored, 92); + + Assert.IsLessThanOrEqualTo(PerceptualHash.DuplicateThreshold, PerceptualHash.Distance(upright, Hash(tagged))); + Assert.IsGreaterThan(PerceptualHash.DuplicateThreshold, PerceptualHash.Distance(upright, Hash(untagged))); + } + + [TestMethod] + public void NonImagesHaveNoHash() + { + Assert.IsNull(PerceptualHash.Compute(new MemoryStream([1, 2, 3, 4, 5]))); + Assert.IsNull(PerceptualHash.Compute(new MemoryStream([]))); + } + + [TestMethod] + public void HashIsStableAcrossRuns() + { + using var scene = TestImages.Scene(3); + var jpeg = TestImages.Jpeg(scene); + Assert.AreEqual(Hash(jpeg), Hash(jpeg)); + Assert.AreEqual(0, PerceptualHash.Distance(5, 5)); + Assert.AreEqual(64, PerceptualHash.Distance(0, ulong.MaxValue)); + } + + [TestMethod] + public void TheIndexComparesOnePhotoWith200000InMilliseconds() + { + var random = new Random(42); + var index = new PerceptualHashIndex(); + var records = new List(200_000); + for (var i = 1; i <= 200_000; i++) + { + records.Add(new PerceptualHashRecord(i, i % 40, (ulong)random.NextInt64() ^ ((ulong)random.Next() << 63))); + } + + index.Load(records); + Assert.AreEqual(200_000, index.Count); + var target = records[123_456].Hash; + var near = target ^ 0b1011UL; // 3 bits away + + index.FindSimilar(near); // warm-up + var best = TimeSpan.MaxValue; + IReadOnlyList matches = []; + for (var run = 0; run < 5; run++) + { + var watch = Stopwatch.StartNew(); + matches = index.FindSimilar(near); + watch.Stop(); + best = watch.Elapsed < best ? watch.Elapsed : best; + } + + TestContext.WriteLine($"Confronto con 200.000 impronte: {best.TotalMilliseconds:F2} ms"); + Assert.IsLessThan(20.0, best.TotalMilliseconds); + Assert.AreEqual(records[123_456].MediaId, matches[0].MediaId); + Assert.AreEqual(3, matches[0].Distance); + } + + [TestMethod] + public void TheIndexPrefersTheTargetAccountAndForgetsRemovedFiles() + { + var index = new PerceptualHashIndex(); + index.Add(1, accountId: 10, hash: 0b0000); + index.Add(2, accountId: 20, hash: 0b0001); + index.Add(3, accountId: 20, hash: 0b0111); + index.Add(4, accountId: 30, hash: ulong.MaxValue); + + var plain = index.FindSimilar(0, maxDistance: 3); + Assert.IsTrue(plain.Select(m => m.MediaId).SequenceEqual([1L, 2L, 3L])); + + var preferred = index.FindSimilar(0, maxDistance: 3, preferAccountId: 20); + Assert.IsTrue(preferred.Select(m => m.MediaId).SequenceEqual([2L, 3L, 1L])); + + Assert.IsTrue(index.Remove(2)); + Assert.IsFalse(index.Remove(2)); + Assert.IsTrue(index.FindSimilar(0, maxDistance: 3, excludeMediaId: 1).Select(m => m.MediaId).SequenceEqual([3L])); + + index.Add(3, accountId: 20, hash: ulong.MaxValue); // replaced + Assert.AreEqual(3, index.Count); + Assert.IsTrue(index.FindSimilar(0, maxDistance: 3).Select(m => m.MediaId).SequenceEqual([1L])); + } +} diff --git a/tests/Febe.Tests/Library/SafeFileWriterTests.cs b/tests/Febe.Tests/Library/SafeFileWriterTests.cs new file mode 100644 index 0000000..57a5a84 --- /dev/null +++ b/tests/Febe.Tests/Library/SafeFileWriterTests.cs @@ -0,0 +1,167 @@ +using System.Security.Cryptography; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Library; + +[TestClass] +public sealed class SafeFileWriterTests +{ + private static byte[] Content(int size, int seed = 1) + { + var bytes = new byte[size]; + new Random(seed).NextBytes(bytes); + return bytes; + } + + [TestMethod] + public async Task WritesTheFileWithItsHashAndPublicationTime() + { + using var temp = new TempFolder(); + var content = Content(300_000); + var published = new DateTimeOffset(2024, 5, 6, 7, 8, 9, TimeSpan.Zero); + var saved = await new SafeFileWriter().SaveAsync(new MemoryStream(content), temp.Path, "post/2024/foto_1.jpg", new SafeWriteOptions { LastWriteTime = published }); + + Assert.AreEqual("post/2024/foto_1.jpg", saved.RelativePath); + Assert.AreEqual(Path.Combine(temp.Path, "post", "2024", "foto_1.jpg"), saved.FullPath); + CollectionAssert.AreEqual(content, await File.ReadAllBytesAsync(saved.FullPath)); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(content)), saved.Sha256); + Assert.AreEqual(content.Length, saved.Bytes); + Assert.IsTrue(saved.LastWriteTimeSet); + Assert.AreEqual(published.UtcDateTime, File.GetLastWriteTimeUtc(saved.FullPath)); + Assert.IsEmpty(Directory.GetFiles(temp.Path, "*.part", SearchOption.AllDirectories)); + } + + [TestMethod] + public async Task NeverOverwritesAnExistingFile() + { + using var temp = new TempFolder(); + var writer = new SafeFileWriter(); + var first = await writer.SaveAsync(new MemoryStream(Content(10, 1)), temp.Path, "post/a.jpg"); + var second = await writer.SaveAsync(new MemoryStream(Content(10, 2)), temp.Path, "post/a.jpg"); + var third = await writer.SaveAsync(new MemoryStream(Content(10, 3)), temp.Path, "post/a.jpg"); + + Assert.AreEqual("post/a.jpg", first.RelativePath); + Assert.AreEqual("post/a (2).jpg", second.RelativePath); + Assert.AreEqual("post/a (3).jpg", third.RelativePath); + CollectionAssert.AreEqual(Content(10, 1), await File.ReadAllBytesAsync(first.FullPath), "Il primo file è rimasto com'era."); + } + + [TestMethod] + public async Task ConcurrentWritesToTheSameNameAllSurvive() + { + using var temp = new TempFolder(); + var writer = new SafeFileWriter(); + var results = await Task.WhenAll(Enumerable.Range(0, 12).Select(i => Task.Run(() => writer.SaveAsync(new MemoryStream(Content(5000, i)), temp.Path, "storie/x.mp4")))); + Assert.AreEqual(12, results.Select(r => r.RelativePath).Distinct().Count()); + foreach (var (result, i) in results.Select((r, i) => (r, i))) + { + CollectionAssert.AreEqual(Content(5000, i), await File.ReadAllBytesAsync(result.FullPath)); + } + } + + [TestMethod] + public async Task UsesATemporaryNameWhileWriting() + { + using var temp = new TempFolder(); + string[]? during = null; + var stream = new ObservingStream(Content(1_000_000), 400_000, () => during = Directory.GetFiles(Path.Combine(temp.Path, "post"))); + await new SafeFileWriter().SaveAsync(stream, temp.Path, "post/finale.jpg"); + + Assert.IsNotNull(during); + Assert.HasCount(1, during); + Assert.IsTrue(SafeFileWriter.IsTemporaryFile(during[0]), during[0]); + Assert.StartsWith(".febe-", Path.GetFileName(during[0])); + Assert.IsTrue(File.Exists(Path.Combine(temp.Path, "post", "finale.jpg"))); + } + + [TestMethod] + public async Task AnInterruptedDownloadLeavesNoFile() + { + using var temp = new TempFolder(); + var broken = new ObservingStream(Content(1_000_000), 300_000, () => throw new IOException("Connessione interrotta")); + await Assert.ThrowsExactlyAsync(() => new SafeFileWriter().SaveAsync(broken, temp.Path, "post/finale.jpg")); + + Assert.IsFalse(File.Exists(Path.Combine(temp.Path, "post", "finale.jpg"))); + Assert.IsEmpty(Directory.GetFiles(temp.Path, "*", SearchOption.AllDirectories)); + } + + [TestMethod] + public async Task ACancelledDownloadLeavesNoFile() + { + using var temp = new TempFolder(); + using var cancel = new CancellationTokenSource(); + var stream = new ObservingStream(Content(1_000_000), 300_000, cancel.Cancel); + await Assert.ThrowsAsync(() => new SafeFileWriter().SaveAsync(stream, temp.Path, "storie/v.mp4", ct: cancel.Token)); + Assert.IsEmpty(Directory.GetFiles(temp.Path, "*", SearchOption.AllDirectories)); + } + + [TestMethod] + public async Task ATooLargeFileIsDropped() + { + using var temp = new TempFolder(); + await Assert.ThrowsExactlyAsync(() => new SafeFileWriter().SaveAsync(new MemoryStream(Content(500_000)), temp.Path, "post/v.mp4", new SafeWriteOptions { MaxBytes = 200_000 })); + Assert.IsEmpty(Directory.GetFiles(temp.Path, "*", SearchOption.AllDirectories)); + } + + [TestMethod] + public async Task TheNameCanDependOnTheHash() + { + using var temp = new TempFolder(); + var content = Content(2048); + var saved = await new SafeFileWriter().SaveAsync(new MemoryStream(content), temp.Path, "profilo", d => $"profilo/{d.Sha256[..8]}_{d.Bytes}.jpg"); + Assert.AreEqual($"profilo/{Convert.ToHexStringLower(SHA256.HashData(content))[..8]}_2048.jpg", saved.RelativePath); + } + + [TestMethod] + public async Task LongNamesAreShortenedAndUnsafeNamesCleaned() + { + using var temp = new TempFolder(); + var writer = new SafeFileWriter(); + var name = "evidenza/" + new string('t', 200) + "/" + new string('n', 200) + "_1.jpg"; + var saved = await writer.SaveAsync(new MemoryStream(Content(10)), temp.Path, name); + Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, saved.FullPath.Length); + Assert.EndsWith(".jpg", saved.RelativePath); + + var reserved = await writer.SaveAsync(new MemoryStream(Content(10)), temp.Path, "post/CON.jpg"); + Assert.AreEqual("post/CON_.jpg", reserved.RelativePath); + + // «..» is not a valid name on Windows: it becomes «_», so nothing can be written outside the folder. + var escape = await writer.SaveAsync(new MemoryStream(Content(10)), temp.Path, "../fuori/a.jpg"); + Assert.AreEqual("_/fuori/a.jpg", escape.RelativePath); + Assert.StartsWith(temp.Path, escape.FullPath); + } + + [TestMethod] + public void CleanupRemovesOnlyTemporaryFiles() + { + using var temp = new TempFolder(); + Directory.CreateDirectory(temp.Combine("post")); + File.WriteAllText(temp.Combine("post", ".febe-abc123.part"), "x"); + File.WriteAllText(temp.Combine(".febe-def456.part"), "x"); + File.WriteAllText(temp.Combine("post", "foto.jpg"), "x"); + File.WriteAllText(temp.Combine("post", "foto.part"), "x"); + Assert.AreEqual(2, SafeFileWriter.CleanupTemporaryFiles(temp.Path)); + Assert.IsTrue(File.Exists(temp.Combine("post", "foto.jpg"))); + Assert.IsTrue(File.Exists(temp.Combine("post", "foto.part"))); + } + + /// A stream that runs an action once, after a given number of bytes has been read. + private sealed class ObservingStream(byte[] data, int triggerAt, Action action) : MemoryStream(data) + { + private bool _fired; + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (!_fired && Position >= triggerAt) + { + _fired = true; + action(); + } + + await Task.Yield(); + cancellationToken.ThrowIfCancellationRequested(); + return await base.ReadAsync(buffer[..Math.Min(buffer.Length, 64 * 1024)], cancellationToken); + } + } +} diff --git a/tests/Febe.Tests/Library/ThumbnailStoreTests.cs b/tests/Febe.Tests/Library/ThumbnailStoreTests.cs new file mode 100644 index 0000000..b07a2f4 --- /dev/null +++ b/tests/Febe.Tests/Library/ThumbnailStoreTests.cs @@ -0,0 +1,143 @@ +using Febe.Core.Library; +using Febe.Tests.Support; +using SkiaSharp; + +namespace Febe.Tests.Library; + +[TestClass] +public sealed class ThumbnailStoreTests +{ + private static SKImageInfo InfoOf(string path) + { + using var codec = SKCodec.Create(path) ?? throw new AssertFailedException("Miniatura non leggibile."); + Assert.AreEqual(SKEncodedImageFormat.Jpeg, codec.EncodedFormat); + return codec.Info; + } + + [TestMethod] + public void ThumbnailsAre480PixelsOnTheLongSideStoredOnceAndSharded() + { + using var temp = new TempFolder(); + var store = new ThumbnailStore(temp.Combine("miniature")); + using var scene = TestImages.Scene(1, 2400, 1600); + var key = Make.Sha(0xAB12); + + Assert.IsTrue(store.Create(key, new MemoryStream(TestImages.Jpeg(scene)))); + var path = store.PathFor(key); + Assert.AreEqual(Path.Combine(temp.Combine("miniature"), key[..2], key + ".jpg"), path); + var info = InfoOf(path); + Assert.AreEqual(480, info.Width); + Assert.AreEqual(320, info.Height); + + var written = File.GetLastWriteTimeUtc(path); + File.SetLastWriteTimeUtc(path, written.AddDays(-1)); + Assert.IsTrue(store.Create(key, new MemoryStream(TestImages.Jpeg(scene)))); + Assert.AreEqual(written.AddDays(-1), File.GetLastWriteTimeUtc(path), "Una miniatura si genera una volta sola."); + Assert.IsTrue(store.Exists(key.ToUpperInvariant())); + } + + [TestMethod] + public void PortraitAndSmallImages() + { + using var temp = new TempFolder(); + var store = new ThumbnailStore(temp.Path); + using var portrait = TestImages.Scene(2, 1080, 1920); + Assert.IsTrue(store.Create(Make.Sha(1), new MemoryStream(TestImages.Jpeg(portrait)))); + var info = InfoOf(store.PathFor(Make.Sha(1))); + Assert.AreEqual(480, info.Height); + Assert.AreEqual(270, info.Width); + + using var small = TestImages.Scene(3, 320, 200); + Assert.IsTrue(store.Create(Make.Sha(2), new MemoryStream(TestImages.Png(small)))); + var smallInfo = InfoOf(store.PathFor(Make.Sha(2))); + Assert.AreEqual(320, smallInfo.Width, "Le immagini piccole non si ingrandiscono."); + } + + [TestMethod] + public void ExifOrientationIsApplied() + { + using var temp = new TempFolder(); + var store = new ThumbnailStore(temp.Path); + using var scene = TestImages.Scene(4, 1200, 900); + using var sideways = TestImages.RotateCounterClockwise(scene); // stored 900 × 1200 + var tagged = TestImages.WithExifOrientation(TestImages.Jpeg(sideways), 6); + + Assert.IsTrue(store.Create(Make.Sha(3), new MemoryStream(tagged))); + var info = InfoOf(store.PathFor(Make.Sha(3))); + Assert.AreEqual(480, info.Width, "Mostrata dritta: più larga che alta."); + Assert.AreEqual(360, info.Height); + } + + [TestMethod] + public void TransparentImagesBecomeJpegOnWhite() + { + using var temp = new TempFolder(); + var store = new ThumbnailStore(temp.Path); + using var transparent = new SKBitmap(new SKImageInfo(600, 600, SKColorType.Rgba8888, SKAlphaType.Premul)); + transparent.Erase(SKColors.Transparent); + Assert.IsTrue(store.Create(Make.Sha(4), new MemoryStream(TestImages.Png(transparent)))); + using var thumbnail = SKBitmap.Decode(store.PathFor(Make.Sha(4))); + var pixel = thumbnail.GetPixel(10, 10); + Assert.IsGreaterThan((byte)240, pixel.Red); + } + + [TestMethod] + public void InvalidContentAndKeysAreRefused() + { + using var temp = new TempFolder(); + var store = new ThumbnailStore(temp.Path); + Assert.IsFalse(store.Create(Make.Sha(5), new MemoryStream([1, 2, 3]))); + Assert.IsFalse(store.Exists(Make.Sha(5))); + Assert.ThrowsExactly(() => store.PathFor("../../etc/passwd")); + Assert.ThrowsExactly(() => store.PathFor("abc")); + } + + [TestMethod] + public void VideosWithoutCoverUseTheNeutralTile() + { + using var temp = new TempFolder(); + var store = new ThumbnailStore(temp.Path); + var tile = store.NeutralVideoTile(); + Assert.AreEqual(Path.Combine(temp.Path, ThumbnailStore.NeutralVideoTileName), tile); + var info = InfoOf(tile); + Assert.AreEqual(480, info.Height); + Assert.AreEqual(tile, store.NeutralVideoTile()); + } + + [TestMethod] + public async Task VideoFramesComeFromFfmpegWhenAvailable() + { + var ffmpeg = VideoFrameExtractor.TryCreate(); + if (ffmpeg is null) + { + Assert.Inconclusive("ffmpeg non è installato: le miniature dei video senza copertina usano la tessera neutra."); + } + + using var temp = new TempFolder(); + var video = temp.Combine("prova.mp4"); + var start = new System.Diagnostics.ProcessStartInfo(ffmpeg.Executable) + { + RedirectStandardError = true, + RedirectStandardOutput = true, + UseShellExecute = false, + }; + foreach (var argument in new[] { "-hide_banner", "-nostdin", "-v", "error", "-f", "lavfi", "-i", "testsrc=duration=2:size=640x360:rate=10", "-pix_fmt", "yuv420p", video }) + { + start.ArgumentList.Add(argument); + } + + using (var process = System.Diagnostics.Process.Start(start)!) + { + await process.WaitForExitAsync(); + Assert.AreEqual(0, process.ExitCode, "ffmpeg non ha creato il video di prova."); + } + + var frame = await ffmpeg.ExtractJpegAsync(video); + Assert.IsNotNull(frame); + var store = new ThumbnailStore(temp.Combine("miniature")); + Assert.IsTrue(store.Create(Make.Sha(6), new MemoryStream(frame))); + Assert.AreEqual(480, InfoOf(store.PathFor(Make.Sha(6))).Width); + + Assert.IsNull(await ffmpeg.ExtractJpegAsync(temp.Combine("non-esiste.mp4"))); + } +} diff --git a/tests/Febe.Tests/Library/WindowsFileNamesTests.cs b/tests/Febe.Tests/Library/WindowsFileNamesTests.cs new file mode 100644 index 0000000..129bf43 --- /dev/null +++ b/tests/Febe.Tests/Library/WindowsFileNamesTests.cs @@ -0,0 +1,124 @@ +using Febe.Core.Library; + +namespace Febe.Tests.Library; + +[TestClass] +public sealed class WindowsFileNamesTests +{ + [TestMethod] + [DataRow("ac:d\"e/f\\g|h?i*j", "a_b_c_d_e_f_g_h_i_j")] + [DataRow("riga\nnuova\ttab\u0001", "riga_nuova_tab_")] + [DataRow("Estate 2025", "Estate 2025")] + [DataRow("caffè & più", "caffè & più")] + [DataRow("nome...", "nome")] + [DataRow("nome . . ", "nome")] + [DataRow(".", "_")] + [DataRow("..", "_")] + [DataRow(" ", "_")] + [DataRow("", "_")] + [DataRow(".nascosto", ".nascosto")] + public void ForbiddenCharactersAndTrailingDotsAreCleaned(string input, string expected) + { + Assert.AreEqual(expected, WindowsFileNames.SanitizeSegment(input)); + } + + [TestMethod] + [DataRow("CON", "CON_")] + [DataRow("con", "con_")] + [DataRow("Nul", "Nul_")] + [DataRow("PRN.jpg", "PRN_.jpg")] + [DataRow("aux.tar.gz", "aux_.tar.gz")] + [DataRow("COM1", "COM1_")] + [DataRow("com9.mp4", "com9_.mp4")] + [DataRow("LPT5", "LPT5_")] + [DataRow("COM\u00B9", "COM\u00B9_")] + [DataRow("LPT\u00B3.txt", "LPT\u00B3_.txt")] + [DataRow("CONIN$", "CONIN$_")] + [DataRow("CON.", "CON_")] + [DataRow("CON .txt", "CON _.txt")] + [DataRow("CONSOLE", "CONSOLE")] + [DataRow("COM10", "COM10")] + [DataRow("icon", "icon")] + public void ReservedNamesAreAvoided(string input, string expected) + { + var result = WindowsFileNames.SanitizeSegment(input); + Assert.AreEqual(expected, result); + Assert.IsFalse(WindowsFileNames.IsReservedName(result)); + } + + [TestMethod] + public void SanitizingIsIdempotent() + { + foreach (var input in new[] { "a:b", "CON", "x. ", "lpt1.jpg", new string('é', 300) + ".jpg", "Ore 10:30 / sera" }) + { + var once = WindowsFileNames.SanitizeSegment(input); + Assert.AreEqual(once, WindowsFileNames.SanitizeSegment(once), input); + } + } + + [TestMethod] + public void LongSegmentsKeepTheirExtension() + { + var name = new string('a', 400) + ".jpg"; + var result = WindowsFileNames.SanitizeSegment(name); + Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxSegmentLength, result.Length); + Assert.EndsWith(".jpg", result); + Assert.Contains("~", result); + } + + [TestMethod] + public void ShortPathsAreLeftAlone() + { + var segments = new[] { "post", "2026", "2026-10-10_18-22-05_DBx3kQ2_2.jpg" }; + CollectionAssert.AreEqual(segments, WindowsFileNames.FitPath(@"D:\Foto\Febe\marta.demo", segments).ToArray()); + } + + [TestMethod] + public void LongPathsAreShortenedKeepingExtensionAndUniqueness() + { + var baseFolder = "/libreria/" + new string('b', 120); + var stem = "2026-10-10_18-22-05_" + new string('C', 120); + var first = WindowsFileNames.FitPath(baseFolder, ["post", "2026", stem + "_1.jpg"]); + var second = WindowsFileNames.FitPath(baseFolder, ["post", "2026", stem + "_2.jpg"]); + + foreach (var fitted in new[] { first, second }) + { + var total = baseFolder.Length + fitted.Sum(s => s.Length + 1); + Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, total); + Assert.EndsWith(".jpg", fitted[^1]); + Assert.AreEqual("post", fitted[0]); + Assert.StartsWith("2026-10-10_18-22-05_", fitted[^1]); + } + + Assert.AreNotEqual(first[^1], second[^1], "Due file diversi restano diversi anche accorciati."); + CollectionAssert.AreEqual(first.ToArray(), WindowsFileNames.FitPath(baseFolder, ["post", "2026", stem + "_1.jpg"]).ToArray(), "Accorciare è deterministico."); + } + + [TestMethod] + public void LongFolderNamesAreShortenedWhenTheFileNameIsNotEnough() + { + var baseFolder = "/libreria/marta.demo"; + var title = "Una raccolta in evidenza con un titolo davvero molto lungo " + new string('x', 200); + var fitted = WindowsFileNames.FitPath(baseFolder, ["evidenza", WindowsFileNames.SanitizeSegment(title), "2025-08-02_10-11-12_3391207_1.jpg"]); + Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, baseFolder.Length + fitted.Sum(s => s.Length + 1)); + Assert.StartsWith("Una raccolta", fitted[1]); + Assert.EndsWith(".jpg", fitted[2]); + } + + [TestMethod] + public void ABaseFolderThatIsTooLongIsReported() + { + var baseFolder = "/" + new string('z', 236); + var error = Assert.ThrowsExactly(() => WindowsFileNames.FitPath(baseFolder, ["post", "a.jpg"])); + Assert.Contains("troppo lunga", error.Message); + } + + [TestMethod] + public void SplitsExtensions() + { + Assert.AreEqual(("foto", ".jpg"), WindowsFileNames.SplitExtension("foto.jpg")); + Assert.AreEqual((".nascosto", string.Empty), WindowsFileNames.SplitExtension(".nascosto")); + Assert.AreEqual(("senza", string.Empty), WindowsFileNames.SplitExtension("senza")); + Assert.AreEqual(("a.b", ".c"), WindowsFileNames.SplitExtension("a.b.c")); + } +} diff --git a/tests/Febe.Tests/Support/LibraryTestSupport.cs b/tests/Febe.Tests/Support/LibraryTestSupport.cs new file mode 100644 index 0000000..55a0443 --- /dev/null +++ b/tests/Febe.Tests/Support/LibraryTestSupport.cs @@ -0,0 +1,253 @@ +using System.Buffers.Binary; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Data; +using SkiaSharp; + +namespace Febe.Tests.Support; + +/// A temporary folder removed at the end of a test. +internal sealed class TempFolder : IDisposable +{ + public TempFolder(string prefix = "febe") + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "febe-prove", prefix + "-" + Guid.NewGuid().ToString("N")[..10]); + Directory.CreateDirectory(Path); + } + + public string Path { get; } + + public string Combine(params string[] parts) => System.IO.Path.Combine([Path, .. parts]); + + public void Dispose() + { + try + { + Directory.Delete(Path, recursive: true); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } +} + +/// A clock moved by hand, in Alberto's zone. +internal sealed class ManualClock(DateTimeOffset start, TimeZoneInfo? zone = null) : IClock +{ + public DateTimeOffset Now { get; set; } = start; + + public TimeZoneInfo LocalZone { get; } = zone ?? TestZones.Rome; + + public Task Delay(TimeSpan time, CancellationToken ct) + { + Now += time; + return Task.CompletedTask; + } +} + +internal static class TestZones +{ + /// Europe/Rome, or an equivalent custom zone when the system has no time zone data. + public static TimeZoneInfo Rome { get; } = LoadRome(); + + private static TimeZoneInfo LoadRome() + { + foreach (var id in new[] { "Europe/Rome", "W. Europe Standard Time" }) + { + try + { + return TimeZoneInfo.FindSystemTimeZoneById(id); + } + catch (TimeZoneNotFoundException) + { + } + catch (InvalidTimeZoneException) + { + } + } + + var start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 5, DayOfWeek.Sunday); + var end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), 10, 5, DayOfWeek.Sunday); + var rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue.Date, DateTime.MaxValue.Date, TimeSpan.FromHours(1), start, end); + return TimeZoneInfo.CreateCustomTimeZone("Europe/Rome", TimeSpan.FromHours(1), "Europe/Rome", "CET", "CEST", [rule]); + } +} + +/// Builders of domain records for tests. +internal static class Make +{ + public static readonly DateTimeOffset T0 = new(2026, 10, 13, 8, 0, 0, TimeSpan.Zero); + + public static Account Account(string username, string? instagramId = null, bool mine = false) => + Core.Domain.Account.Create(username, StartingPoint.EverythingAndKeepUpdated, T0, TestZones.Rome, isMine: mine) with + { + InstagramId = instagramId ?? ((uint)username.GetHashCode(StringComparison.Ordinal)).ToString(System.Globalization.CultureInfo.InvariantCulture), + }; + + public static Entry Entry(long accountId, string instagramId, DateTimeOffset publishedAt, EntryKind kind = EntryKind.Post, string? caption = null) => new() + { + AccountId = accountId, + Kind = kind, + InstagramId = instagramId, + Code = "C" + instagramId, + PublishedAt = publishedAt, + Caption = caption, + DiscoveredAt = T0, + }; + + public static Media Photo(int position = 1, MediaState state = MediaState.ToDownload) => + new() { Position = position, Kind = MediaKind.Photo, State = state, Width = 1080, Height = 1350 }; + + public static Media Video(int position = 1, MediaState state = MediaState.ToDownload) => + new() { Position = position, Kind = MediaKind.Video, State = state, Width = 1080, Height = 1920, Duration = TimeSpan.FromSeconds(15) }; + + public static Media Stored(Media media, string sha, string path) => + media with { State = MediaState.Downloaded, Sha256 = sha, RelativePath = path, Bytes = 1000 }; + + public static string Sha(int n) => n.ToString("x64", System.Globalization.CultureInfo.InvariantCulture); +} + +/// Opens test databases. +internal static class TestDatabase +{ + public static Task OpenAsync(TempFolder folder, string name = "dati") => FebeDatabase.OpenAsync(folder.Combine(name)); +} + +/// Generated images: «photos» made of gradients, shapes, lines and grain, reproducible from a seed. +internal static class TestImages +{ + public static SKBitmap Scene(int seed, int width = 1200, int height = 900) + { + var random = new Random(seed); + var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul)); + using var canvas = new SKCanvas(bitmap); + SKColor RandomColor() => new((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256)); + + using (var background = new SKPaint()) + { + var angle = random.NextDouble() * Math.PI * 2; + var dx = (float)Math.Cos(angle) * width / 2; + var dy = (float)Math.Sin(angle) * height / 2; + background.Shader = SKShader.CreateLinearGradient( + new SKPoint((width / 2f) - dx, (height / 2f) - dy), + new SKPoint((width / 2f) + dx, (height / 2f) + dy), + [RandomColor(), RandomColor(), RandomColor()], + null, + SKShaderTileMode.Clamp); + canvas.DrawRect(0, 0, width, height, background); + } + + using var paint = new SKPaint { IsAntialias = true }; + var shapes = 10 + random.Next(10); + for (var i = 0; i < shapes; i++) + { + paint.Color = RandomColor().WithAlpha((byte)(160 + random.Next(96))); + paint.Style = random.Next(4) == 0 ? SKPaintStyle.Stroke : SKPaintStyle.Fill; + paint.StrokeWidth = 4 + random.Next(30); + var x = (float)(random.NextDouble() * width); + var y = (float)(random.NextDouble() * height); + var w = (float)((0.05 + (random.NextDouble() * 0.4)) * width); + var h = (float)((0.05 + (random.NextDouble() * 0.4)) * height); + switch (random.Next(4)) + { + case 0: + canvas.DrawRect(x - (w / 2), y - (h / 2), w, h, paint); + break; + case 1: + canvas.DrawCircle(x, y, Math.Min(w, h) / 2, paint); + break; + case 2: + canvas.DrawOval(new SKRect(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2)), paint); + break; + default: + paint.StrokeWidth = 6 + random.Next(20); + canvas.DrawLine(x, y, (float)(random.NextDouble() * width), (float)(random.NextDouble() * height), paint); + break; + } + } + + // Fine grain, as in a photo. + using var grain = new SKPaint { IsAntialias = false }; + for (var i = 0; i < width * height / 60; i++) + { + var v = (byte)random.Next(256); + grain.Color = new SKColor(v, v, v, 28); + canvas.DrawPoint(random.Next(width), random.Next(height), grain); + } + + return bitmap; + } + + public static byte[] Jpeg(SKBitmap bitmap, int quality = 90) + { + using var image = SKImage.FromBitmap(bitmap); + using var data = image.Encode(SKEncodedImageFormat.Jpeg, quality); + return data.ToArray(); + } + + public static byte[] Png(SKBitmap bitmap) + { + using var image = SKImage.FromBitmap(bitmap); + using var data = image.Encode(SKEncodedImageFormat.Png, 100); + return data.ToArray(); + } + + public static SKBitmap Resize(SKBitmap source, int width, int height) + { + var result = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul)); + using var canvas = new SKCanvas(result); + using var image = SKImage.FromBitmap(source); + canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null); + return result; + } + + public static SKBitmap Crop(SKBitmap source, SKRectI area) + { + var result = new SKBitmap(new SKImageInfo(area.Width, area.Height, SKColorType.Rgba8888, SKAlphaType.Premul)); + using var canvas = new SKCanvas(result); + using var image = SKImage.FromBitmap(source); + canvas.DrawImage(image, area, new SKRect(0, 0, area.Width, area.Height), new SKSamplingOptions(SKFilterMode.Nearest), null); + return result; + } + + /// Decodes a JPEG/PNG back to a bitmap. + public static SKBitmap Decode(byte[] encoded) => SKBitmap.Decode(encoded) ?? throw new InvalidOperationException("decode"); + + /// Rotates pixels 90° counter-clockwise (what a camera stores before tagging orientation 6). + public static SKBitmap RotateCounterClockwise(SKBitmap source) + { + var result = new SKBitmap(new SKImageInfo(source.Height, source.Width, SKColorType.Rgba8888, SKAlphaType.Premul)); + using var canvas = new SKCanvas(result); + canvas.Translate(0, source.Width); + canvas.RotateDegrees(-90); + canvas.DrawBitmap(source, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest), null); + return result; + } + + /// Inserts an EXIF APP1 segment with the given orientation right after the SOI marker of a JPEG. + public static byte[] WithExifOrientation(byte[] jpeg, ushort orientation) + { + if (jpeg.Length < 2 || jpeg[0] != 0xFF || jpeg[1] != 0xD8) + { + throw new ArgumentException("Not a JPEG.", nameof(jpeg)); + } + + var app1 = new byte[36]; + app1[0] = 0xFF; + app1[1] = 0xE1; + BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(2), 34); // length, including these two bytes + "Exif\0\0"u8.CopyTo(app1.AsSpan(4)); + "MM\0*"u8.CopyTo(app1.AsSpan(10)); // TIFF header, big endian + BinaryPrimitives.WriteUInt32BigEndian(app1.AsSpan(14), 8); // offset of IFD0 + BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(18), 1); // one entry + BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(20), 0x0112); // Orientation + BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(22), 3); // SHORT + BinaryPrimitives.WriteUInt32BigEndian(app1.AsSpan(24), 1); // count + BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(28), orientation); + BinaryPrimitives.WriteUInt32BigEndian(app1.AsSpan(32), 0); // no next IFD + return [.. jpeg.AsSpan(0, 2), .. app1, .. jpeg.AsSpan(2)]; + } +} diff --git a/tests/Febe.Tests/Support/TestLibrary.cs b/tests/Febe.Tests/Support/TestLibrary.cs new file mode 100644 index 0000000..572685e --- /dev/null +++ b/tests/Febe.Tests/Support/TestLibrary.cs @@ -0,0 +1,96 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Data; + +namespace Febe.Tests.Support; + +/// A library with its Data folder, database and services, in a temporary folder. +internal sealed class TestLibrary : IAsyncDisposable +{ + private TestLibrary(TempFolder temp, FebeDatabase db, ManualClock clock) + { + Temp = temp; + Db = db; + Clock = clock; + Data = new DataFolderLayout(temp.Combine("dati")); + Layout = new LibraryLayout(temp.Combine("libreria")); + Thumbnails = new ThumbnailStore(Data.Thumbnails); + Index = new PerceptualHashIndex(); + Journal = new AccountJournal(clock); + Ingest = new LibraryIngest(db, Layout, LibraryNaming.Default, Journal, clock, Thumbnails, Index); + } + + public TempFolder Temp { get; } + + public FebeDatabase Db { get; private set; } + + public ManualClock Clock { get; } + + public DataFolderLayout Data { get; } + + public LibraryLayout Layout { get; } + + public ThumbnailStore Thumbnails { get; } + + public PerceptualHashIndex Index { get; } + + public AccountJournal Journal { get; } + + public LibraryIngest Ingest { get; private set; } + + public static async Task CreateAsync(TempFolder temp) + { + var db = await FebeDatabase.OpenAsync(temp.Combine("dati")); + return new TestLibrary(temp, db, new ManualClock(Make.T0)); + } + + /// Records an entry and stores its files as the collection pipeline would, then writes the journal line. + public async Task SaveAsync(Account account, Entry entry, IReadOnlyList files, string? highlightTitle = null) + { + var added = await Db.Entries.AddAsync(entry, files.Select(f => f.Media).ToList()); + foreach (var (media, file) in added.Stored.Media.Zip(files.OrderBy(f => f.Media.Position))) + { + await Ingest.SaveMediaAsync(account, added.Stored.Entry, media, new MediaContent { Content = new MemoryStream(file.Bytes), Extension = file.Extension }, highlightTitle); + } + + await Ingest.AppendJournalAsync(added.Stored.Entry.Id); + return (await Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!; + } + + /// Simulates the loss of the database: closes it, deletes the file and opens an empty one. + public async Task LoseDatabaseAsync() + { + await Db.DisposeAsync(); + foreach (var suffix in new[] { string.Empty, "-wal", "-shm" }) + { + File.Delete(Data.Database + suffix); + } + + Db = await FebeDatabase.OpenAsync(Data.Root); + Ingest = new LibraryIngest(Db, Layout, LibraryNaming.Default, Journal, Clock, Thumbnails, Index); + } + + public ValueTask DisposeAsync() => Db.DisposeAsync(); +} + +/// A file to store: its record and its bytes. +internal sealed record TestFile(Media Media, byte[] Bytes, string Extension) +{ + private static int videoSeed; + + public static TestFile Photo(int position, int scene, int width = 1080, int height = 1350) => + new(Make.Photo(position), PhotoBytes(scene, width, height), ".jpg"); + + public static TestFile Video(int position, int size = 50_000) + { + var bytes = new byte[size]; + new Random(Interlocked.Increment(ref videoSeed)).NextBytes(bytes); + return new TestFile(Make.Video(position), bytes, ".mp4"); + } + + public static byte[] PhotoBytes(int scene, int width = 1080, int height = 1350) + { + using var bitmap = TestImages.Scene(scene, width, height); + return TestImages.Jpeg(bitmap, 88); + } +}