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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
69 files changed
+12472
No files matched your search
@@ -0,0 +1,216 @@
|
||||
namespace Febe.Core.Domain;
|
||||
|
||||
/// <summary>«Quanto indietro nel tempo» (spec §4.4).</summary>
|
||||
public enum HistoryDepth
|
||||
{
|
||||
/// <summary>Tutto: the whole history.</summary>
|
||||
All,
|
||||
|
||||
/// <summary>Ultimi N post: only the most recent <see cref="AccountLimits.LastPosts"/> posts.</summary>
|
||||
LastPosts,
|
||||
|
||||
/// <summary>Da una data: only content published from <see cref="AccountLimits.FromDate"/> onward.</summary>
|
||||
FromDate,
|
||||
}
|
||||
|
||||
/// <summary>Why an account is «Non raggiungibile» (spec §4.2).</summary>
|
||||
public enum UnreachableReason
|
||||
{
|
||||
/// <summary>Private profile that Alberto does not follow: never touched (rule 6).</summary>
|
||||
PrivateNotFollowed,
|
||||
|
||||
/// <summary>The profile does not exist (any more).</summary>
|
||||
NotFound,
|
||||
|
||||
/// <summary>The profile blocked Alberto or is restricted.</summary>
|
||||
Blocked,
|
||||
|
||||
/// <summary>A profile that is not followed changed name: Alberto must indicate the new one.</summary>
|
||||
Renamed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notices that put an account in the «Da controllare» filter together with the Unreachable state (spec §4.2).
|
||||
/// They stay until Alberto acknowledges them.
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum AccountNotices
|
||||
{
|
||||
None = 0,
|
||||
|
||||
/// <summary>The profile changed name: Febe updated it and kept the folder.</summary>
|
||||
Renamed = 1,
|
||||
|
||||
/// <summary>A reader met a response format it did not recognize (spec §6.4).</summary>
|
||||
UnrecognizedFormat = 2,
|
||||
}
|
||||
|
||||
/// <summary>Per-account limits (spec §4.4 «Limiti»). Account and general limits apply together: the stricter wins.</summary>
|
||||
public sealed record AccountLimits
|
||||
{
|
||||
public HistoryDepth Depth { get; init; } = HistoryDepth.All;
|
||||
|
||||
/// <summary>Number of most recent posts to keep when <see cref="Depth"/> is <see cref="HistoryDepth.LastPosts"/>.</summary>
|
||||
public int? LastPosts { get; init; }
|
||||
|
||||
/// <summary>First instant (UTC) of the period to download when <see cref="Depth"/> is <see cref="HistoryDepth.FromDate"/>.</summary>
|
||||
public DateTimeOffset? FromDate { get; init; }
|
||||
|
||||
/// <summary>«Storico, massimo al giorno»: backfill posts per day for this account.</summary>
|
||||
public int BackfillPostsPerDay { get; init; } = CautionProfile.Prudent.BackfillPostsPerAccountPerDay;
|
||||
|
||||
/// <summary>Videos larger than this are skipped. Null means no limit (the default).</summary>
|
||||
public long? MaxVideoBytes { get; init; }
|
||||
|
||||
/// <summary>«Scarica anche i video delle storie».</summary>
|
||||
public bool StoryVideos { get; init; } = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An Instagram account that Febe archives (spec §4.2, §4.4, §8.3).
|
||||
/// <para>
|
||||
/// The identity of an account is its numeric Instagram identifier (<see cref="InstagramId"/>), never the user name:
|
||||
/// a renamed profile keeps its row, its entries and its folder. <see cref="Id"/> is the local row key used by the
|
||||
/// database and by <c>IGovernor</c>; it exists because accounts created by the import («Solo archivio») may not know
|
||||
/// their Instagram identifier yet.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed record Account
|
||||
{
|
||||
/// <summary>Local key (0 until stored).</summary>
|
||||
public long Id { get; init; }
|
||||
|
||||
/// <summary>Numeric Instagram identifier, as text. Unique when present; null only for archive-only accounts.</summary>
|
||||
public string? InstagramId { get; init; }
|
||||
|
||||
public required string Username { get; init; }
|
||||
|
||||
public string? DisplayName { get; init; }
|
||||
|
||||
public bool IsPrivate { get; init; }
|
||||
|
||||
/// <summary>Alberto follows this profile.</summary>
|
||||
public bool IsFollowed { get; init; }
|
||||
|
||||
/// <summary>Alberto's own profile («Tu»). At most one account has it.</summary>
|
||||
public bool IsMine { get; init; }
|
||||
|
||||
public AccountState State { get; init; } = AccountState.UpToDate;
|
||||
|
||||
/// <summary>When <see cref="State"/> last changed (e.g. «Messo in pausa da te il 2 ottobre»).</summary>
|
||||
public DateTimeOffset? StateChangedAt { get; init; }
|
||||
|
||||
public UnreachableReason? UnreachableReason { get; init; }
|
||||
|
||||
/// <summary>«Tieni aggiornato». With false a single download is made, then the account stays paused.</summary>
|
||||
public bool KeepUpdated { get; init; } = true;
|
||||
|
||||
public Frequency Frequency { get; init; } = Frequency.Normal;
|
||||
|
||||
/// <summary>«Su misura»: how often to check posts.</summary>
|
||||
public TimeSpan? CustomPostInterval { get; init; }
|
||||
|
||||
/// <summary>«Su misura»: maximum interval between two story checks.</summary>
|
||||
public TimeSpan? CustomStoryInterval { get; init; }
|
||||
|
||||
/// <summary>«Cosa scaricare».</summary>
|
||||
public ContentTypes ContentTypes { get; init; } = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Stories
|
||||
| ContentTypes.Highlights | ContentTypes.ProfilePicture;
|
||||
|
||||
public AccountLimits Limits { get; init; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Folder of the account. Null means the default <c><Libreria>/<username></c>; 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 <c>Febe.Core.Library.LibraryLayout.AccountFolder</c>.
|
||||
/// </summary>
|
||||
public string? Folder { get; init; }
|
||||
|
||||
/// <summary>Opaque resume point of the backfill (Storico), written by the collection pipeline.</summary>
|
||||
public string? BackfillCursor { get; init; }
|
||||
|
||||
/// <summary>When the backfill reached the limit or the oldest post.</summary>
|
||||
public DateTimeOffset? BackfillCompletedAt { get; init; }
|
||||
|
||||
/// <summary>Number of posts declared by the profile, when known (used to estimate the backfill).</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>Last user name before a rename.</summary>
|
||||
public string? PreviousUsername { get; init; }
|
||||
|
||||
public DateTimeOffset? RenamedAt { get; init; }
|
||||
|
||||
/// <summary>Last time a reader met an unknown format for this account.</summary>
|
||||
public DateTimeOffset? FormatUnrecognizedAt { get; init; }
|
||||
|
||||
public required DateTimeOffset AddedAt { get; init; }
|
||||
|
||||
/// <summary>True for the «Da controllare» filter: unreachable, renamed or with an unrecognized format.</summary>
|
||||
public bool NeedsAttention => State == AccountState.Unreachable || Notices != AccountNotices.None;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="username">User name.</param>
|
||||
/// <param name="startingPoint">One of the three starting points.</param>
|
||||
/// <param name="now">Current time (from IClock).</param>
|
||||
/// <param name="zone">Alberto's time zone: «da oggi» starts at local midnight.</param>
|
||||
/// <param name="profile">Caution profile in use (defaults to Prudente).</param>
|
||||
/// <param name="isMine">Alberto's own profile: «Post in cui è taggato» is on.</param>
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
namespace Febe.Core.Domain;
|
||||
|
||||
/// <summary>Where a probable duplicate was found.</summary>
|
||||
public enum DuplicateOrigin
|
||||
{
|
||||
/// <summary>A file just downloaded looks like one already in the library (spec §9.5).</summary>
|
||||
Download,
|
||||
|
||||
/// <summary>A file of an import looks like one in the library or in the same source (spec §9.3).</summary>
|
||||
Import,
|
||||
}
|
||||
|
||||
/// <summary>Why two files are probable duplicates (spec §9.3).</summary>
|
||||
public enum DuplicateReason
|
||||
{
|
||||
/// <summary>Same Instagram identifier, different file.</summary>
|
||||
SameInstagramId,
|
||||
|
||||
/// <summary>Very close perceptual hashes.</summary>
|
||||
VisuallySimilar,
|
||||
}
|
||||
|
||||
/// <summary>Alberto's decision on a probable duplicate. No choice is made in advance (mockup 09).</summary>
|
||||
public enum DuplicateDecision
|
||||
{
|
||||
Pending,
|
||||
|
||||
/// <summary>«Tieni il più grande». If the larger is the new one it replaces a library file: an explicit choice (rule 12).</summary>
|
||||
KeepLarger,
|
||||
|
||||
/// <summary>«Tieni quello in libreria».</summary>
|
||||
KeepExisting,
|
||||
|
||||
/// <summary>«Tienili entrambi».</summary>
|
||||
KeepBoth,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A pair of files that are probably the same content, waiting for Alberto's decision (spec §8.3 <c>duplicate_pair</c>).
|
||||
/// Each side is either a library file (<c>*MediaId</c>) or a file of an import (<c>*ImportFileId</c>): exactly one per side.
|
||||
/// The existing side is the library file (or, for duplicates inside a source, the first file met).
|
||||
/// </summary>
|
||||
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; }
|
||||
|
||||
/// <summary>Hamming distance of the perceptual hashes, when the reason is visual.</summary>
|
||||
public int? Distance { get; init; }
|
||||
|
||||
public DuplicateDecision Decision { get; init; } = DuplicateDecision.Pending;
|
||||
|
||||
public required DateTimeOffset CreatedAt { get; init; }
|
||||
|
||||
public DateTimeOffset? DecidedAt { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Core.Domain;
|
||||
|
||||
/// <summary>What a queued engine task does: one recipe of spec §6.3 on one account (or none).</summary>
|
||||
public enum EngineTaskKind
|
||||
{
|
||||
/// <summary>Giro dei seguiti: home and stories bar.</summary>
|
||||
FollowingSweep,
|
||||
|
||||
/// <summary>Storie di un account.</summary>
|
||||
AccountStories,
|
||||
|
||||
/// <summary>Controllo del profilo.</summary>
|
||||
ProfileCheck,
|
||||
|
||||
/// <summary>Storico.</summary>
|
||||
Backfill,
|
||||
|
||||
/// <summary>Raccolta in evidenza.</summary>
|
||||
HighlightCheck,
|
||||
|
||||
/// <summary>Scheda Taggati.</summary>
|
||||
TaggedCheck,
|
||||
|
||||
/// <summary>Scheda Reel.</summary>
|
||||
ReelsCheck,
|
||||
|
||||
/// <summary>Post singolo (also to refresh an expired address).</summary>
|
||||
SinglePost,
|
||||
|
||||
/// <summary>Elenco dei seguiti, on request only.</summary>
|
||||
FollowingList,
|
||||
}
|
||||
|
||||
public enum EngineTaskState
|
||||
{
|
||||
Pending,
|
||||
Running,
|
||||
Done,
|
||||
Failed,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// <summary>A task of the engine queue (spec §8.3 <c>task</c>). Persisted so that a restart resets nothing.</summary>
|
||||
public sealed record EngineTask
|
||||
{
|
||||
public long Id { get; init; }
|
||||
|
||||
public required EngineTaskKind Kind { get; init; }
|
||||
|
||||
public long? AccountId { get; init; }
|
||||
|
||||
/// <summary>Not before this instant.</summary>
|
||||
public required DateTimeOffset DueAt { get; init; }
|
||||
|
||||
/// <summary>Higher runs first among due tasks («Controlla ora» goes on top).</summary>
|
||||
public int Priority { get; init; }
|
||||
|
||||
public EngineTaskState State { get; init; } = EngineTaskState.Pending;
|
||||
|
||||
/// <summary>Optional arguments (e.g. a post code), as compact text or JSON. Never secrets.</summary>
|
||||
public string? Payload { get; init; }
|
||||
|
||||
/// <summary>Asked by Alberto (spec §7.8).</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One counted action toward the site (spec §7.4 <c>action_log</c>): the basis of the budgets. For
|
||||
/// <see cref="ActionKind.DataDownload"/> <see cref="Amount"/> is a number of bytes; otherwise it is normally 1.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Usage of one budget category: rolling last 60 minutes and current local calendar day.</summary>
|
||||
public readonly record struct BudgetUsage(long LastHour, long Today);
|
||||
|
||||
public enum SessionOutcome
|
||||
{
|
||||
/// <summary>Still open.</summary>
|
||||
Running,
|
||||
|
||||
/// <summary>Ended normally.</summary>
|
||||
Completed,
|
||||
|
||||
/// <summary>Closed by a throttle signal.</summary>
|
||||
Throttled,
|
||||
|
||||
/// <summary>Stopped by a challenge or disconnection, or by Alberto.</summary>
|
||||
Stopped,
|
||||
|
||||
/// <summary>The program ended while it was open.</summary>
|
||||
Interrupted,
|
||||
|
||||
/// <summary>Ended by an unexpected error.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>A session of the engine (spec §7.2, §8.3 <c>session</c>): feeds the strip of the day.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Short Italian summary for the interface (no captions, no addresses with signatures).</summary>
|
||||
public string? Summary { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A stop of the circuit breaker (spec §7.6, §8.3 <c>incident</c>).</summary>
|
||||
public sealed record Incident
|
||||
{
|
||||
public long Id { get; init; }
|
||||
|
||||
public required DateTimeOffset At { get; init; }
|
||||
|
||||
public required SignalLevel Level { get; init; }
|
||||
|
||||
/// <summary>Signal code, e.g. "http-429" (from segnali.json).</summary>
|
||||
public required string Signal { get; init; }
|
||||
|
||||
/// <summary>Address where it was seen, without query string.</summary>
|
||||
public string? Url { get; init; }
|
||||
|
||||
/// <summary>For throttles: the stop lasts until this instant.</summary>
|
||||
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,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A line of the readable timeline of the interface (spec §8.3 <c>event</c>). <see cref="Message"/> is Italian and
|
||||
/// never contains captions, response bodies, cookies or signed addresses.
|
||||
/// </summary>
|
||||
public sealed record EventRecord
|
||||
{
|
||||
public long Id { get; init; }
|
||||
|
||||
public required DateTimeOffset At { get; init; }
|
||||
|
||||
public EventSeverity Severity { get; init; } = EventSeverity.Info;
|
||||
|
||||
/// <summary>Stable machine code, e.g. "storico-completato".</summary>
|
||||
public required string Code { get; init; }
|
||||
|
||||
public required string Message { get; init; }
|
||||
|
||||
public long? AccountId { get; init; }
|
||||
|
||||
public long? SessionId { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A profile of the list Alberto follows, as last read (spec §4.2, §8.3 <c>following</c>).</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>Position in the list as read.</summary>
|
||||
public int Position { get; init; }
|
||||
|
||||
public required DateTimeOffset ReadAt { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Domain;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="Media"/> rows.
|
||||
/// <para>
|
||||
/// 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).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed record Entry
|
||||
{
|
||||
/// <summary>Local key (0 until stored).</summary>
|
||||
public long Id { get; init; }
|
||||
|
||||
public required long AccountId { get; init; }
|
||||
|
||||
public required EntryKind Kind { get; init; }
|
||||
|
||||
/// <summary>Instagram identifier, as text. Null only for imported entries that were not recognized.</summary>
|
||||
public string? InstagramId { get; init; }
|
||||
|
||||
/// <summary>Post code (short code), when the kind has one.</summary>
|
||||
public string? Code { get; init; }
|
||||
|
||||
/// <summary>Publication time, UTC.</summary>
|
||||
public required DateTimeOffset PublishedAt { get; init; }
|
||||
|
||||
/// <summary>Caption. Never written to logs (spec §13.2).</summary>
|
||||
public string? Caption { get; init; }
|
||||
|
||||
/// <summary>Author's user name, for tagged posts (the author is someone else).</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>When Alberto deleted it from the library (state <see cref="EntryState.Deleted"/>).</summary>
|
||||
public DateTimeOffset? DeletedAt { get; init; }
|
||||
|
||||
/// <summary>For stories: when the story stops being available on the site (downloads give them precedence).</summary>
|
||||
public DateTimeOffset? ExpiresAt { get; init; }
|
||||
|
||||
/// <summary>The value of the <c>{codice}</c> placeholder (spec §4.3) for this entry.</summary>
|
||||
/// <param name="sha256">SHA-256 of the file, needed for profile pictures (first eight hex digits).</param>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An entry with its files, in position order.</summary>
|
||||
public sealed record EntryWithMedia(Entry Entry, IReadOnlyList<Media> Media);
|
||||
|
||||
/// <summary>Derives the state of an entry from the states of its files.</summary>
|
||||
public static class EntryStateRules
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static EntryState FromMedia(EntryState current, Provenance provenance, IReadOnlyCollection<MediaState> 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;
|
||||
}
|
||||
|
||||
/// <summary>States whose entries appear in the library mosaic (they have at least one file).</summary>
|
||||
public static IReadOnlyList<EntryState> Visible { get; } = [EntryState.Downloaded, EntryState.Partial, EntryState.Imported];
|
||||
|
||||
/// <summary>True when the file state means a file is on disk.</summary>
|
||||
public static bool IsPresent(MediaState state) => state is MediaState.Downloaded or MediaState.Imported;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace Febe.Core.Domain;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public sealed record Highlight
|
||||
{
|
||||
/// <summary>Local key (0 until stored).</summary>
|
||||
public long Id { get; init; }
|
||||
|
||||
public required long AccountId { get; init; }
|
||||
|
||||
/// <summary>Instagram identifier of the collection. Null for collections known only from an import.</summary>
|
||||
public string? InstagramId { get; init; }
|
||||
|
||||
/// <summary>Title shown on the profile: the <c>{raccolta}</c> placeholder.</summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>Order on the profile, from 0.</summary>
|
||||
public int Position { get; init; }
|
||||
|
||||
public required DateTimeOffset DiscoveredAt { get; init; }
|
||||
|
||||
public DateTimeOffset? LastCheckedAt { get; init; }
|
||||
|
||||
/// <summary>The collection disappeared from the profile. Its files stay (rule 12).</summary>
|
||||
public DateTimeOffset? RemovedAt { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>An entry inside a highlight collection, with its position (from 0).</summary>
|
||||
public sealed record HighlightItem(long HighlightId, long EntryId, int Position);
|
||||
@@ -0,0 +1,181 @@
|
||||
namespace Febe.Core.Domain;
|
||||
|
||||
/// <summary>State of an import (spec §9.1: source, analysis, review, copy).</summary>
|
||||
public enum ImportRunState
|
||||
{
|
||||
/// <summary>Passo 2: read-only analysis in progress.</summary>
|
||||
Analyzing,
|
||||
|
||||
/// <summary>Analysis interrupted: resumes from where it was.</summary>
|
||||
AnalysisInterrupted,
|
||||
|
||||
/// <summary>Passo 3: waiting for Alberto's review.</summary>
|
||||
Reviewing,
|
||||
|
||||
/// <summary>Passo 4: copy or move in progress.</summary>
|
||||
Copying,
|
||||
|
||||
/// <summary>Copy interrupted: resumes from where it was.</summary>
|
||||
CopyInterrupted,
|
||||
|
||||
Completed,
|
||||
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// <summary>«Copia» (default) or «Sposta» (the original is deleted only after the copy is verified with SHA-256).</summary>
|
||||
public enum ImportMode
|
||||
{
|
||||
Copy,
|
||||
Move,
|
||||
}
|
||||
|
||||
/// <summary>Result of the comparison with the library (spec §9.3).</summary>
|
||||
public enum ImportOutcome
|
||||
{
|
||||
/// <summary>Not analyzed yet.</summary>
|
||||
Pending,
|
||||
|
||||
/// <summary>«Nuovo»: will be copied.</summary>
|
||||
New,
|
||||
|
||||
/// <summary>«Già in libreria»: same SHA-256 as a file present in any account. Skipped.</summary>
|
||||
AlreadyInLibrary,
|
||||
|
||||
/// <summary>«Doppione probabile»: same Instagram identifier with a different file, or very close perceptual hash.</summary>
|
||||
ProbableDuplicate,
|
||||
|
||||
/// <summary>«Non riconosciuto»: neither a photo nor a video. Ignored and listed.</summary>
|
||||
Unrecognized,
|
||||
}
|
||||
|
||||
/// <summary>Alberto's decision for a file of an import.</summary>
|
||||
public enum ImportDecision
|
||||
{
|
||||
/// <summary>Follow the outcome (new files are imported, the others are not).</summary>
|
||||
None,
|
||||
|
||||
Import,
|
||||
|
||||
Skip,
|
||||
|
||||
KeepLarger,
|
||||
|
||||
KeepExisting,
|
||||
|
||||
KeepBoth,
|
||||
}
|
||||
|
||||
/// <summary>Progress of one file of an import. Persisted so that an interrupted import resumes (spec §9.4).</summary>
|
||||
public enum ImportFileState
|
||||
{
|
||||
Pending,
|
||||
Analyzed,
|
||||
Copied,
|
||||
Moved,
|
||||
Skipped,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>Where the date of an imported file came from (spec §9.2, in this order of preference).</summary>
|
||||
public enum ImportDateSource
|
||||
{
|
||||
FileName,
|
||||
Metadata,
|
||||
ModifiedTime,
|
||||
}
|
||||
|
||||
/// <summary>An import (spec §8.3 <c>import_run</c>).</summary>
|
||||
public sealed record ImportRun
|
||||
{
|
||||
public long Id { get; init; }
|
||||
|
||||
/// <summary>Source folder (Windows: chosen folder; Docker: a subfolder of /importa).</summary>
|
||||
public required string SourcePath { get; init; }
|
||||
|
||||
/// <summary>The source cannot be written: «Sposta» is not offered.</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>A file of an import with its analysis, outcome and decision (spec §8.3 <c>import_file</c>).</summary>
|
||||
public sealed record ImportFile
|
||||
{
|
||||
public long Id { get; init; }
|
||||
|
||||
public required long RunId { get; init; }
|
||||
|
||||
/// <summary>Path relative to the source folder, '/' separated.</summary>
|
||||
public required string RelativePath { get; init; }
|
||||
|
||||
/// <summary>Source subfolder (relative, '/' separated, empty for the root): the unit of account association.</summary>
|
||||
public required string Folder { get; init; }
|
||||
|
||||
public long Bytes { get; init; }
|
||||
|
||||
public DateTimeOffset? ModifiedAt { get; init; }
|
||||
|
||||
/// <summary>Photo or video from the content; null when not recognized.</summary>
|
||||
public MediaKind? MediaKind { get; init; }
|
||||
|
||||
/// <summary>Detected content type, e.g. "image/jpeg".</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>Probable account, from the folder name.</summary>
|
||||
public string? ProbableAccount { get; init; }
|
||||
|
||||
/// <summary>Probable kind (story, highlight, tagged) from the subfolders.</summary>
|
||||
public EntryKind? ProbableKind { get; init; }
|
||||
|
||||
/// <summary>Probable highlight collection title, from the subfolders.</summary>
|
||||
public string? HighlightTitle { get; init; }
|
||||
|
||||
public ImportOutcome Outcome { get; init; } = ImportOutcome.Pending;
|
||||
|
||||
/// <summary>The library file this one matches (already in library or probable duplicate).</summary>
|
||||
public long? MatchedMediaId { get; init; }
|
||||
|
||||
/// <summary>Account the folder is associated with in the review.</summary>
|
||||
public long? TargetAccountId { get; init; }
|
||||
|
||||
public ImportDecision Decision { get; init; } = ImportDecision.None;
|
||||
|
||||
public ImportFileState State { get; init; } = ImportFileState.Pending;
|
||||
|
||||
/// <summary>Entry created or completed by the copy.</summary>
|
||||
public long? EntryId { get; init; }
|
||||
|
||||
/// <summary>Path of the copy relative to the account folder.</summary>
|
||||
public string? DestinationPath { get; init; }
|
||||
|
||||
public string? LastError { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
namespace Febe.Core.Domain;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class LocalCalendar
|
||||
{
|
||||
/// <summary>Local calendar day of an instant.</summary>
|
||||
public static DateOnly Today(DateTimeOffset instant, TimeZoneInfo zone) =>
|
||||
DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(instant, zone).DateTime);
|
||||
|
||||
/// <summary>Local wall-clock time of an instant.</summary>
|
||||
public static DateTime ToLocal(DateTimeOffset instant, TimeZoneInfo zone) =>
|
||||
TimeZoneInfo.ConvertTime(instant, zone).DateTime;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static DateTimeOffset StartOfDay(DateOnly day, TimeZoneInfo zone) =>
|
||||
FromLocal(day.ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified), zone);
|
||||
|
||||
/// <summary>[start, end) of a local day, as UTC instants.</summary>
|
||||
public static (DateTimeOffset Start, DateTimeOffset End) DayBounds(DateOnly day, TimeZoneInfo zone) =>
|
||||
(StartOfDay(day, zone), StartOfDay(day.AddDays(1), zone));
|
||||
|
||||
/// <summary>[start, end) of the local day containing <paramref name="instant"/>.</summary>
|
||||
public static (DateTimeOffset Start, DateTimeOffset End) DayBounds(DateTimeOffset instant, TimeZoneInfo zone) =>
|
||||
DayBounds(Today(instant, zone), zone);
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Domain;
|
||||
|
||||
/// <summary>
|
||||
/// A file («file», spec §4.3): one photo or one video of an entry. Unique per (entry, position).
|
||||
/// </summary>
|
||||
public sealed record Media
|
||||
{
|
||||
/// <summary>Local key (0 until stored).</summary>
|
||||
public long Id { get; init; }
|
||||
|
||||
/// <summary>Owning entry (set by the store when the entry is added).</summary>
|
||||
public long EntryId { get; init; }
|
||||
|
||||
/// <summary>Position in the series, from 1: the <c>{n}</c> placeholder.</summary>
|
||||
public required int Position { get; init; }
|
||||
|
||||
public required MediaKind Kind { get; init; }
|
||||
|
||||
/// <summary>Instagram identifier of this item of a series, when the site gives one.</summary>
|
||||
public string? InstagramId { get; init; }
|
||||
|
||||
public int? Width { get; init; }
|
||||
|
||||
public int? Height { get; init; }
|
||||
|
||||
/// <summary>Video duration.</summary>
|
||||
public TimeSpan? Duration { get; init; }
|
||||
|
||||
public MediaState State { get; init; } = MediaState.ToDownload;
|
||||
|
||||
/// <summary>Path relative to the account folder, with '/' separators. Null while not on disk.</summary>
|
||||
public string? RelativePath { get; init; }
|
||||
|
||||
public long? Bytes { get; init; }
|
||||
|
||||
/// <summary>SHA-256 of the file, lowercase hex: exact duplicates and thumbnail key.</summary>
|
||||
public string? Sha256 { get; init; }
|
||||
|
||||
/// <summary>64-bit perceptual hash, for photos only (spec §8.4).</summary>
|
||||
public ulong? PerceptualHash { get; init; }
|
||||
|
||||
/// <summary>A thumbnail exists under Dati/miniature for <see cref="Sha256"/>.</summary>
|
||||
public bool HasThumbnail { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public string? SourceUrl { get; init; }
|
||||
|
||||
/// <summary>Address of the video cover image given by the page (thumbnail source for videos).</summary>
|
||||
public string? CoverUrl { get; init; }
|
||||
|
||||
/// <summary>When <see cref="SourceUrl"/> was read from the page.</summary>
|
||||
public DateTimeOffset? SourceSeenAt { get; init; }
|
||||
|
||||
public int Attempts { get; init; }
|
||||
|
||||
/// <summary>Last error, in Italian, without addresses or secrets.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A file together with where it lives: used by exact-duplicate lookups across the library.</summary>
|
||||
public sealed record MediaLocation(Media Media, Entry Entry, string Username);
|
||||
|
||||
/// <summary>A file waiting for the download queue (spec §6.5), with what the queue needs to order it.</summary>
|
||||
public sealed record PendingDownload(Media Media, long AccountId, EntryKind Kind, DateTimeOffset PublishedAt, DateTimeOffset? ExpiresAt);
|
||||
|
||||
/// <summary>What the safe writer and the hashing produced for a file now on disk.</summary>
|
||||
/// <param name="RelativePath">Path relative to the account folder, '/' separated.</param>
|
||||
/// <param name="Bytes">Size.</param>
|
||||
/// <param name="Sha256">Lowercase hex SHA-256.</param>
|
||||
/// <param name="PerceptualHash">Perceptual hash for photos.</param>
|
||||
/// <param name="Width">Width in pixels, when known.</param>
|
||||
/// <param name="Height">Height in pixels, when known.</param>
|
||||
/// <param name="Duration">Video duration, when known.</param>
|
||||
/// <param name="HasThumbnail">A thumbnail was stored.</param>
|
||||
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);
|
||||
Reference in new issue
Block a user