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);
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Operations recorded in <c>_febe.jsonl</c>.</summary>
|
||||
public static class JournalOps
|
||||
{
|
||||
/// <summary>An entry was saved (or completed): one line per saved entry.</summary>
|
||||
public const string Save = "save";
|
||||
|
||||
/// <summary>An entry was deleted from the library by Alberto.</summary>
|
||||
public const string Delete = "delete";
|
||||
}
|
||||
|
||||
/// <summary>Account identity in a journal line.</summary>
|
||||
public sealed record JournalAccount(string? Id, string Username, string? DisplayName = null, bool? IsMine = null);
|
||||
|
||||
/// <summary>A highlight collection an entry belongs to.</summary>
|
||||
public sealed record JournalHighlight(string? Id, string Title, int? Position = null);
|
||||
|
||||
/// <summary>Entry data in a journal line. <see cref="Kind"/> is the folder name of the kind («post», «storie», ...).</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>"downloaded" or "imported".</summary>
|
||||
public string? Provenance { get; init; }
|
||||
|
||||
public DateTimeOffset? ExpiresAt { get; init; }
|
||||
|
||||
public IReadOnlyList<JournalHighlight>? Highlights { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A file in a journal line; <see cref="Path"/> is relative to the account folder, '/' separated.</summary>
|
||||
public sealed record JournalFile
|
||||
{
|
||||
public required int N { get; init; }
|
||||
|
||||
/// <summary>"photo" or "video".</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>One line of <c>_febe.jsonl</c> (format version 1).</summary>
|
||||
public sealed record JournalLine
|
||||
{
|
||||
public int V { get; init; } = AccountJournal.FormatVersion;
|
||||
|
||||
/// <summary><see cref="JournalOps.Save"/> or <see cref="JournalOps.Delete"/>.</summary>
|
||||
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<JournalFile>? Files { get; init; }
|
||||
|
||||
/// <summary>Delete only: true when the deletion is remembered (the entry must not come back).</summary>
|
||||
public bool? Remember { get; init; }
|
||||
|
||||
/// <summary>The entry kind of this line, or null for an unknown kind name.</summary>
|
||||
[JsonIgnore]
|
||||
public EntryKind? Kind => EntryKindNames.FromFolder(Entry.Kind);
|
||||
}
|
||||
|
||||
/// <summary>Content of a journal: the valid lines in order, and how many lines could not be read.</summary>
|
||||
public sealed record JournalContent(IReadOnlyList<JournalLine> Lines, int InvalidLines);
|
||||
|
||||
/// <summary>
|
||||
/// The journal of an account folder, <c>_febe.jsonl</c> (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 (<see cref="LibraryRebuilder"/>).
|
||||
/// </summary>
|
||||
public sealed class AccountJournal(IClock clock)
|
||||
{
|
||||
/// <summary>File name inside each account folder.</summary>
|
||||
public const string FileName = "_febe.jsonl";
|
||||
|
||||
public const int FormatVersion = 1;
|
||||
|
||||
private static readonly ConcurrentDictionary<string, SemaphoreSlim> 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,
|
||||
};
|
||||
|
||||
/// <summary>Path of the journal of an account folder.</summary>
|
||||
public static string PathFor(string accountFolder) => Path.Combine(accountFolder, FileName);
|
||||
|
||||
/// <summary>Appends the line of a saved entry: the files present (downloaded or imported) with their metadata.</summary>
|
||||
public Task AppendSavedAsync(
|
||||
string accountFolder,
|
||||
Account account,
|
||||
Entry entry,
|
||||
IReadOnlyList<Media> media,
|
||||
IReadOnlyList<JournalHighlight>? 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the line of a deletion. With <paramref name="remember"/> the entry stays known and is not downloaded
|
||||
/// again; without it («Eliminalo e lascia che torni») it may come back.
|
||||
/// </summary>
|
||||
public Task AppendDeletedAsync(
|
||||
string accountFolder,
|
||||
Account account,
|
||||
Entry entry,
|
||||
IReadOnlyList<string> 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);
|
||||
}
|
||||
|
||||
/// <summary>Appends a line. Lines of one file are serialized; a line cut by a crash never merges with the next.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads a journal. Unreadable lines (e.g. cut by a crash) are counted and skipped.</summary>
|
||||
public static async Task<JournalContent> ReadAsync(string accountFolder, CancellationToken ct = default)
|
||||
{
|
||||
var path = PathFor(accountFolder);
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return new JournalContent([], 0);
|
||||
}
|
||||
|
||||
var lines = new List<JournalLine>();
|
||||
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;
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A daily copy of the database.</summary>
|
||||
public sealed record BackupFile(DateOnly Day, string Path, long Bytes);
|
||||
|
||||
/// <summary>Result of a daily backup run.</summary>
|
||||
/// <param name="Created">The copy made now, or null when today's copy already existed.</param>
|
||||
/// <param name="Removed">Copies removed by the retention.</param>
|
||||
public sealed record BackupResult(BackupFile? Created, IReadOnlyList<string> Removed);
|
||||
|
||||
/// <summary>
|
||||
/// Daily copy of the database (spec §8.5): <c>VACUUM INTO</c> a new file <c>Dati/copie/febe-YYYY-MM-DD.sqlite</c>
|
||||
/// (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 <c>febe-YYYY-MM-DD.sqlite</c> are ever removed.
|
||||
/// </summary>
|
||||
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();
|
||||
|
||||
/// <summary>The backups folder.</summary>
|
||||
public string Folder { get; } = Path.GetFullPath(backupsFolder);
|
||||
|
||||
/// <summary>File name of the copy of a day.</summary>
|
||||
public static string FileNameFor(DateOnly day) => Prefix + day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + Extension;
|
||||
|
||||
/// <summary>Makes today's copy if missing, then applies the retention. Safe to call often.</summary>
|
||||
public async Task<BackupResult> 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));
|
||||
}
|
||||
|
||||
/// <summary>The copies present, newest first.</summary>
|
||||
public IReadOnlyList<BackupFile> List()
|
||||
{
|
||||
if (!Directory.Exists(Folder))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var list = new List<BackupFile>();
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes copies older than <see cref="DefaultKeepDays"/> days (today included) and stale temporary copies.
|
||||
/// Returns the removed paths.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> ApplyRetention(DateOnly today)
|
||||
{
|
||||
var removed = new List<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The day of a backup file name, or null for any other file.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>What is wrong with the Data folder.</summary>
|
||||
public enum DataFolderProblemKind
|
||||
{
|
||||
/// <summary>On a network share: SQLite in WAL mode and the browser profile do not work there (spec §8.2).</summary>
|
||||
NetworkPath,
|
||||
|
||||
/// <summary>The folder cannot be written.</summary>
|
||||
NotWritable,
|
||||
|
||||
/// <summary>The folder does not exist and cannot be created.</summary>
|
||||
CannotCreate,
|
||||
|
||||
/// <summary>The path names a file, not a folder.</summary>
|
||||
NotAFolder,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed record DataFolderProblem(
|
||||
DataFolderProblemKind Kind,
|
||||
string Path,
|
||||
string Title,
|
||||
string Explanation,
|
||||
string Remedy,
|
||||
string? FileSystem = null);
|
||||
|
||||
/// <summary>A mounted file system (a line of /proc/mounts).</summary>
|
||||
public sealed record MountEntry(string Device, string MountPoint, string FileSystemType);
|
||||
|
||||
/// <summary>Reads mount tables (Linux <c>/proc/mounts</c>).</summary>
|
||||
public static class MountTable
|
||||
{
|
||||
/// <summary>
|
||||
/// File system types that live on another machine. <c>9p</c> is included: it is how WSL and some virtual machines
|
||||
/// share host folders, and SQLite's locking is not reliable on it.
|
||||
/// </summary>
|
||||
public static IReadOnlySet<string> NetworkFileSystems { get; } = new HashSet<string>(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);
|
||||
}
|
||||
|
||||
/// <summary>Parses the content of /proc/mounts (or /etc/mtab). Malformed lines are skipped.</summary>
|
||||
public static IReadOnlyList<MountEntry> Parse(string content)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var entries = new List<MountEntry>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The mount that contains a path: the longest mount point that is a prefix of it (later mounts win ties).</summary>
|
||||
public static MountEntry? FindContaining(IReadOnlyList<MountEntry> 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;
|
||||
}
|
||||
|
||||
/// <summary>Decodes the octal escapes of /proc/mounts (<c>\040</c> space, <c>\011</c> tab, <c>\012</c> newline, <c>\134</c> backslash).</summary>
|
||||
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';
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class DataFolderCheck
|
||||
{
|
||||
private readonly Func<string?> _readMounts;
|
||||
|
||||
/// <param name="readMounts">Source of the mount table (tests inject one); by default /proc/mounts on Linux.</param>
|
||||
public DataFolderCheck(Func<string?>? readMounts = null) => _readMounts = readMounts ?? ReadProcMounts;
|
||||
|
||||
/// <summary>The first problem of the folder, or null when it is fine. Creates the folder if missing.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A network-path problem for a full path, or null when the path is local.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True for Windows network paths: <c>\\server\share</c>, <c>//server/share</c> and <c>\\?\UNC\server\share</c>.
|
||||
/// Device paths to local drives (<c>\\?\C:\</c>, <c>\\.\C:\</c>) are not network paths.
|
||||
/// </summary>
|
||||
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.";
|
||||
|
||||
/// <summary>The path with symbolic links of its existing part resolved, so the right mount is found.</summary>
|
||||
private static string ResolveExisting(string fullPath)
|
||||
{
|
||||
var current = fullPath;
|
||||
var suffix = new Stack<string>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
using SkiaSharp;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static class ImageDecoding
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public const long MaxDecodedPixels = 100_000_000;
|
||||
|
||||
/// <summary>
|
||||
/// Decodes an image upright, as premultiplied RGBA. When <paramref name="minLongSide"/> 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Dimensions of an image as displayed (orientation applied), without decoding the pixels.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>The two choices of the deletion dialog (spec §4.6).</summary>
|
||||
public enum DeletionMode
|
||||
{
|
||||
/// <summary>
|
||||
/// Default, «ricorda la scelta»: the entry stays in the database without files, in the state «eliminato», so it is
|
||||
/// never downloaded again.
|
||||
/// </summary>
|
||||
Remember,
|
||||
|
||||
/// <summary>«Eliminalo e lascia che torni»: the record is removed too; a later check may download it again.</summary>
|
||||
AllowReturn,
|
||||
}
|
||||
|
||||
/// <summary>What a deletion did.</summary>
|
||||
/// <param name="EntryId">The entry.</param>
|
||||
/// <param name="Found">False when the entry did not exist (nothing done).</param>
|
||||
/// <param name="DeletedFiles">Files removed from disk (relative paths).</param>
|
||||
/// <param name="MissingFiles">Files that were already missing.</param>
|
||||
/// <param name="FailedFiles">Files that could not be removed (e.g. open in another program), with the reason.</param>
|
||||
public sealed record DeletionResult(
|
||||
long EntryId,
|
||||
bool Found,
|
||||
IReadOnlyList<string> DeletedFiles,
|
||||
IReadOnlyList<string> MissingFiles,
|
||||
IReadOnlyList<string> FailedFiles)
|
||||
{
|
||||
public bool Complete => Found && FailedFiles.Count == 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «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).
|
||||
/// <para>
|
||||
/// Order: the deletion line goes to <c>_febe.jsonl</c> first (so a rebuild honours it even if Febe stops halfway),
|
||||
/// then the database, then the files and their thumbnails.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class LibraryDeletion(
|
||||
IFebeStorage storage,
|
||||
LibraryLayout layout,
|
||||
AccountJournal journal,
|
||||
IClock clock,
|
||||
ThumbnailStore? thumbnails = null,
|
||||
PerceptualHashIndex? hashIndex = null)
|
||||
{
|
||||
public async Task<DeletionResult> 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<string>();
|
||||
var missing = new List<string>();
|
||||
var failed = new List<string>();
|
||||
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<string>().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);
|
||||
}
|
||||
|
||||
/// <summary>Multiple selection: deletes each entry in turn.</summary>
|
||||
public async Task<IReadOnlyList<DeletionResult>> DeleteManyAsync(IEnumerable<long> entryIds, DeletionMode mode = DeletionMode.Remember, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entryIds);
|
||||
var results = new List<DeletionResult>();
|
||||
foreach (var id in entryIds.Distinct())
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
results.Add(await DeleteAsync(id, mode, ct).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>The content of one file to store, as received (download) or read (import).</summary>
|
||||
public sealed record MediaContent
|
||||
{
|
||||
public required Stream Content { get; init; }
|
||||
|
||||
/// <summary>File extension, e.g. ".jpg" or ".mp4" (from the content type or the address).</summary>
|
||||
public required string Extension { get; init; }
|
||||
|
||||
/// <summary>For videos: the cover image given by the page, used for the thumbnail.</summary>
|
||||
public Stream? Cover { get; init; }
|
||||
|
||||
/// <summary>Drop the file beyond this size («Salta i video oltre», spec §4.4).</summary>
|
||||
public long? MaxBytes { get; init; }
|
||||
}
|
||||
|
||||
public enum MediaSaveOutcome
|
||||
{
|
||||
/// <summary>The file is in the library and its record is updated.</summary>
|
||||
Stored,
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
IdenticalInAccount,
|
||||
}
|
||||
|
||||
/// <summary>What <see cref="LibraryIngest.SaveMediaAsync"/> did.</summary>
|
||||
/// <param name="Outcome">Stored or discarded.</param>
|
||||
/// <param name="File">The stored file, when stored.</param>
|
||||
/// <param name="Identical">The file already present, when discarded.</param>
|
||||
/// <param name="SimilarPairs">Probable duplicates recorded for Alberto (same account, close perceptual hash).</param>
|
||||
public sealed record MediaSaveResult(MediaSaveOutcome Outcome, StoredFile? File, MediaLocation? Identical, IReadOnlyList<DuplicatePair> SimilarPairs);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>_febe.jsonl</c> 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.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// Stores one file of an entry already recorded in the database (<paramref name="media"/> must have its key).
|
||||
/// </summary>
|
||||
/// <param name="account">Owner of the entry.</param>
|
||||
/// <param name="entry">The entry.</param>
|
||||
/// <param name="media">The file record to fill.</param>
|
||||
/// <param name="content">The bytes and their extension.</param>
|
||||
/// <param name="highlightTitle">For highlight items: the collection title (<c>{raccolta}</c>).</param>
|
||||
/// <param name="ct">Cancellation: an interrupted save leaves nothing behind.</param>
|
||||
/// <exception cref="FileTooLargeException">
|
||||
/// The content exceeded <see cref="MediaContent.MaxBytes"/>: nothing was written; the caller marks the file
|
||||
/// <see cref="MediaState.Skipped"/> with <see cref="IMediaStore.MarkFailedAsync"/>.
|
||||
/// </exception>
|
||||
/// <exception cref="IOException">Writing failed (disk full, connection cut): nothing was written under the final name.</exception>
|
||||
public async Task<MediaSaveResult> 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<DuplicatePair>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the <c>_febe.jsonl</c> 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).
|
||||
/// </summary>
|
||||
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<Stream> 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class LibraryLayout
|
||||
{
|
||||
public LibraryLayout(string libraryRoot, int maxPathLength = WindowsFileNames.MaxPathLength)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(libraryRoot);
|
||||
Root = Path.GetFullPath(libraryRoot);
|
||||
MaxPathLength = maxPathLength;
|
||||
}
|
||||
|
||||
/// <summary>Full path of the library folder.</summary>
|
||||
public string Root { get; }
|
||||
|
||||
public int MaxPathLength { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Folder of an account: <see cref="Account.Folder"/> when absolute; relative to the library when relative;
|
||||
/// otherwise <c><Libreria>/<username></c> (spec §4.4).
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The value to store in <see cref="Account.Folder"/> 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.
|
||||
/// </summary>
|
||||
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, '/');
|
||||
}
|
||||
|
||||
/// <summary>Full path of a file of an account from its stored relative path.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The relative path (with '/') of a new file, rendered with the naming scheme and fitted to the path length limit
|
||||
/// inside the account folder.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>'/'-separated relative path → platform separators.</summary>
|
||||
public static string ToPlatform(string relativePath) =>
|
||||
relativePath.Replace('\\', '/').Replace('/', Path.DirectorySeparatorChar);
|
||||
|
||||
/// <summary>Platform relative path → '/'-separated (the stored form).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The Data folder (spec §8.2): database, browser profile, thumbnails, backups, logs.</summary>
|
||||
public sealed record DataFolderLayout
|
||||
{
|
||||
public DataFolderLayout(string root)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(root);
|
||||
Root = Path.GetFullPath(root);
|
||||
}
|
||||
|
||||
public string Root { get; }
|
||||
|
||||
/// <summary>Dati/febe.sqlite.</summary>
|
||||
public string Database => Path.Combine(Root, "febe.sqlite");
|
||||
|
||||
/// <summary>Dati/browser: holds the Instagram session.</summary>
|
||||
public string BrowserProfile => Path.Combine(Root, "browser");
|
||||
|
||||
/// <summary>Dati/miniature.</summary>
|
||||
public string Thumbnails => Path.Combine(Root, "miniature");
|
||||
|
||||
/// <summary>Dati/copie: daily database backups.</summary>
|
||||
public string Backups => Path.Combine(Root, "copie");
|
||||
|
||||
/// <summary>Dati/registro: rotating logs.</summary>
|
||||
public string Logs => Path.Combine(Root, "registro");
|
||||
|
||||
/// <summary>Dati/segnali.json.</summary>
|
||||
public string SignalsFile => Path.Combine(Root, "segnali.json");
|
||||
}
|
||||
@@ -0,0 +1,623 @@
|
||||
using System.Security.Cryptography;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>Options of «Ricostruisci il database dalla libreria».</summary>
|
||||
public sealed record RebuildOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> ExtraAccountFolders { get; init; } = [];
|
||||
|
||||
/// <summary>Create missing thumbnails (photos; videos with ffmpeg when available).</summary>
|
||||
public bool CreateThumbnails { get; init; } = true;
|
||||
|
||||
/// <summary>Files hashed in parallel.</summary>
|
||||
public int Parallelism { get; init; } = Math.Max(1, Environment.ProcessorCount);
|
||||
}
|
||||
|
||||
/// <summary>Progress of a rebuild.</summary>
|
||||
public sealed record RebuildProgress(string Folder, int FoldersDone, int FoldersTotal, int FilesChecked);
|
||||
|
||||
/// <summary>What a rebuild found and did.</summary>
|
||||
public sealed record RebuildReport
|
||||
{
|
||||
public int AccountFolders { get; init; }
|
||||
|
||||
/// <summary>Folders of the library without <c>_febe.jsonl</c>: not rebuilt (their files can be imported).</summary>
|
||||
public IReadOnlyList<string> FoldersWithoutJournal { get; init; } = [];
|
||||
|
||||
public int AccountsCreated { get; init; }
|
||||
|
||||
public int AccountsMatched { get; init; }
|
||||
|
||||
public int EntriesCreated { get; init; }
|
||||
|
||||
/// <summary>Entries already in the database (a rebuild over an existing database only adds what is missing).</summary>
|
||||
public int EntriesAlreadyPresent { get; init; }
|
||||
|
||||
/// <summary>Remembered deletions restored as «eliminato»: those entries are not downloaded again.</summary>
|
||||
public int EntriesDeleted { get; init; }
|
||||
|
||||
public int FilesVerified { get; init; }
|
||||
|
||||
public int FilesMissing { get; init; }
|
||||
|
||||
/// <summary>Files whose SHA-256 differs from the journal (the file on disk wins).</summary>
|
||||
public int HashMismatches { get; init; }
|
||||
|
||||
/// <summary>Files in account folders that no journal line mentions: left untouched, not added.</summary>
|
||||
public int UntrackedFiles { get; init; }
|
||||
|
||||
public int InvalidLines { get; init; }
|
||||
|
||||
/// <summary>A few examples of what needs attention (Italian), for the report screen.</summary>
|
||||
public IReadOnlyList<string> Notes { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Ricostruisci il database dalla libreria» (spec §8.5): reads every account folder and its <c>_febe.jsonl</c>,
|
||||
/// 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.
|
||||
/// <para>
|
||||
/// 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.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
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<RebuildReport> RebuildAsync(RebuildOptions? options = null, IProgress<RebuildProgress>? progress = null, CancellationToken ct = default)
|
||||
{
|
||||
options ??= new RebuildOptions();
|
||||
var report = new Accumulator();
|
||||
var folders = new List<string>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private async Task<List<Item>> SplitPresentAsync(Account account, List<Item> 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<Item>();
|
||||
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<Account> ResolveAccountAsync(string folder, IReadOnlyList<JournalLine> 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);
|
||||
}
|
||||
|
||||
/// <summary>Replays the journal: the last save of an entry wins, deletions remove it or mark it.</summary>
|
||||
private static List<Item> Fold(IReadOnlyList<JournalLine> lines, Accumulator report)
|
||||
{
|
||||
var order = new List<Item>();
|
||||
var byKey = new Dictionary<string, Item>(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<FileCheck> 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<Item> items, Accumulator report)
|
||||
{
|
||||
var known = new HashSet<string>(
|
||||
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<int, JournalFile> Files { get; } = [];
|
||||
|
||||
public bool Deleted { get; set; }
|
||||
|
||||
public DateTimeOffset? DeletedAt { get; set; }
|
||||
}
|
||||
|
||||
private sealed class Accumulator
|
||||
{
|
||||
private readonly List<string> _notes = [];
|
||||
|
||||
public int AccountFolders { get; set; }
|
||||
|
||||
public List<string> 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>setting</c> table.
|
||||
/// </summary>
|
||||
public sealed record LibrarySettings(string LibraryRoot, LibraryNaming Naming, bool SetFileTimeToPublication = true)
|
||||
{
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public static async Task<LibrarySettings> 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);
|
||||
}
|
||||
|
||||
/// <summary>Stores the settings in one transaction.</summary>
|
||||
public Task SaveAsync(ISettingsStore store, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
return store.SetManyAsync(
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
[SettingKeys.LibraryRoot] = LibraryRoot,
|
||||
[SettingKeys.NamingScheme] = Naming.General.Text,
|
||||
[SettingKeys.HighlightNamingScheme] = Naming.Highlight.Text,
|
||||
[SettingKeys.SetFileTimeToPublication] = SetFileTimeToPublication ? "true" : "false",
|
||||
},
|
||||
ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>A file of the preview tree.</summary>
|
||||
public sealed record NamingPreviewFile(string Name, MediaKind Kind);
|
||||
|
||||
/// <summary>A folder of the preview tree: its path below the account folder and the files in it.</summary>
|
||||
public sealed record NamingPreviewFolder(IReadOnlyList<string> Path, IReadOnlyList<NamingPreviewFile> Files);
|
||||
|
||||
/// <summary>
|
||||
/// 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 « \ ».
|
||||
/// </summary>
|
||||
public sealed record NamingPreview(
|
||||
string AccountFolder,
|
||||
IReadOnlyList<NamingPreviewFolder> Folders,
|
||||
IReadOnlyList<string> Errors,
|
||||
IReadOnlyList<string> Warnings)
|
||||
{
|
||||
public bool IsValid => Errors.Count == 0;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <paramref name="zone"/>, so the preview reads the same anywhere.
|
||||
/// </summary>
|
||||
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<NamingPreviewFolder>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// A naming scheme of the library (spec §4.7), e.g. <c>{account}\{tipo}\{anno}\{data}_{ora}_{codice}_{n}</c>.
|
||||
/// <para>
|
||||
/// A backslash (or a slash) separates folders on every operating system. Placeholders: <c>account</c>, <c>tipo</c>,
|
||||
/// <c>anno</c>, <c>mese</c>, <c>data</c>, <c>ora</c>, <c>codice</c>, <c>n</c>, <c>raccolta</c> (only in the scheme of
|
||||
/// highlight collections). Dates and times are in Alberto's time zone: <c>data</c> is yyyy-MM-dd and <c>ora</c> is
|
||||
/// HH-mm-ss. The file extension is added to the last segment.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The scheme is rendered inside the folder of the account: when it starts with the segment <c>{account}</c>, that
|
||||
/// segment <em>is</em> the account folder (which may be elsewhere, spec §4.4) and is not repeated.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
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}";
|
||||
|
||||
/// <summary>Placeholders accepted, in the order shown in the interface.</summary>
|
||||
public static IReadOnlyList<string> Placeholders { get; } = ["account", "tipo", "anno", "mese", "data", "ora", "codice", "n", "raccolta"];
|
||||
|
||||
private readonly IReadOnlyList<IReadOnlyList<Token>> _segments;
|
||||
|
||||
private NamingScheme(string text, bool forHighlights, IReadOnlyList<IReadOnlyList<Token>> segments)
|
||||
{
|
||||
Text = text;
|
||||
ForHighlights = forHighlights;
|
||||
_segments = segments;
|
||||
}
|
||||
|
||||
/// <summary>The scheme as written.</summary>
|
||||
public string Text { get; }
|
||||
|
||||
/// <summary>True for the scheme of highlight collections (accepts <c>{raccolta}</c>).</summary>
|
||||
public bool ForHighlights { get; }
|
||||
|
||||
public static NamingScheme General { get; } = Parse(DefaultGeneral, forHighlights: false);
|
||||
|
||||
public static NamingScheme Highlight { get; } = Parse(DefaultHighlight, forHighlights: true);
|
||||
|
||||
/// <summary>Parses a scheme. </summary>
|
||||
/// <exception cref="FormatException">The scheme is not valid; the message (Italian) says why.</exception>
|
||||
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!;
|
||||
}
|
||||
|
||||
/// <summary>Checks a scheme for the settings screen: errors block saving, warnings are shown.</summary>
|
||||
public static NamingSchemeValidation Validate(string? text, bool forHighlights)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
var warnings = new List<string>();
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return new NamingSchemeValidation(null, ["Lo schema è vuoto."], []);
|
||||
}
|
||||
|
||||
var rawSegments = text.Trim().Split(['\\', '/']);
|
||||
var segments = new List<IReadOnlyList<Token>>();
|
||||
var used = new HashSet<string>(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="WindowsFileNames.FitPath"/> or <see cref="LibraryLayout"/> to apply the
|
||||
/// length limit.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Render(NamingValues values, TimeZoneInfo zone)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
ArgumentNullException.ThrowIfNull(zone);
|
||||
var local = LocalCalendar.ToLocal(values.PublishedAt, zone);
|
||||
var result = new List<string>(_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;
|
||||
}
|
||||
|
||||
/// <summary>Renders the path relative to the account folder with '/' separators (the form stored in the database).</summary>
|
||||
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<Token> Tokenize(string segment, List<string> errors)
|
||||
{
|
||||
var tokens = new List<Token>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Result of <see cref="NamingScheme.Validate"/>.</summary>
|
||||
public sealed record NamingSchemeValidation(NamingScheme? Scheme, IReadOnlyList<string> Errors, IReadOnlyList<string> Warnings)
|
||||
{
|
||||
public bool IsValid => Scheme is not null && Errors.Count == 0;
|
||||
}
|
||||
|
||||
/// <summary>Values of the placeholders for one file.</summary>
|
||||
/// <param name="Account">User name of the account (<c>{account}</c>).</param>
|
||||
/// <param name="Kind">Kind of the entry (<c>{tipo}</c>).</param>
|
||||
/// <param name="PublishedAt">Publication time; rendered in Alberto's zone.</param>
|
||||
/// <param name="Code">The <c>{codice}</c> value: see <see cref="Entry.NameCode"/>.</param>
|
||||
/// <param name="Position">Position of the file in the entry, from 1 (<c>{n}</c>).</param>
|
||||
/// <param name="Extension">File extension, with or without the dot (e.g. ".jpg").</param>
|
||||
/// <param name="Collection">Title of the highlight collection (<c>{raccolta}</c>).</param>
|
||||
public sealed record NamingValues(
|
||||
string Account,
|
||||
EntryKind Kind,
|
||||
DateTimeOffset PublishedAt,
|
||||
string Code,
|
||||
int Position,
|
||||
string Extension,
|
||||
string? Collection = null)
|
||||
{
|
||||
/// <summary>Values for a file of an entry.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The two configurable schemes (spec §4.7): general and for highlight collections.</summary>
|
||||
public sealed record LibraryNaming(NamingScheme General, NamingScheme Highlight)
|
||||
{
|
||||
public static LibraryNaming Default { get; } = new(NamingScheme.General, NamingScheme.Highlight);
|
||||
|
||||
/// <summary>The scheme that applies to an entry kind.</summary>
|
||||
public NamingScheme For(EntryKind kind) => kind == EntryKind.Highlight ? Highlight : General;
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
using System.Numerics;
|
||||
using SkiaSharp;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// 64-bit perceptual hash of photos (spec §8.4, «impronta visiva»): the classic DCT pHash.
|
||||
/// <list type="number">
|
||||
/// <item>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);</item>
|
||||
/// <item>a 2-D DCT-II is computed and the 8×8 lowest frequencies are kept;</item>
|
||||
/// <item>each of the 64 coefficients gives a bit: 1 when above the median of the 64.</item>
|
||||
/// </list>
|
||||
/// Two photos are probable duplicates when the Hamming distance of their hashes is at most
|
||||
/// <see cref="DuplicateThreshold"/>. Videos have no perceptual hash: for them only SHA-256 counts (spec §9.3).
|
||||
/// </summary>
|
||||
public static class PerceptualHash
|
||||
{
|
||||
/// <summary>
|
||||
/// Maximum Hamming distance (out of 64 bits) for two photos to be probable duplicates.
|
||||
/// <para>
|
||||
/// Calibrated on 2026-10-13 by <c>Febe.Tests.Library.PerceptualHashTests</c> on 24 generated scenes (gradients,
|
||||
/// shapes, lines and grain; 1200×900 and 900×1200), each compared with its variants:
|
||||
/// <list type="bullet">
|
||||
/// <item>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 <b>4</b> (only the 96-px reduction; all others ≤ 2);</item>
|
||||
/// <item>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 <b>8</b>;</item>
|
||||
/// <item>different scenes: smallest distance <b>20</b> (average 31).</item>
|
||||
/// </list>
|
||||
/// 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).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public const int DuplicateThreshold = 6;
|
||||
|
||||
private const int Size = 32;
|
||||
private const int Low = 8;
|
||||
|
||||
private static readonly double[,] Cosines = BuildCosines();
|
||||
|
||||
/// <summary>Hamming distance between two hashes (0–64).</summary>
|
||||
public static int Distance(ulong a, ulong b) => BitOperations.PopCount(a ^ b);
|
||||
|
||||
/// <summary>True when two hashes are within <see cref="DuplicateThreshold"/>.</summary>
|
||||
public static bool AreSimilar(ulong a, ulong b, int threshold = DuplicateThreshold) => Distance(a, b) <= threshold;
|
||||
|
||||
/// <summary>Hash of an encoded image; null when the content is not a decodable image.</summary>
|
||||
public static ulong? Compute(Stream encodedImage)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(encodedImage);
|
||||
using var bitmap = ImageDecoding.DecodeUpright(encodedImage, minLongSide: 256);
|
||||
return bitmap is null ? null : Compute(bitmap);
|
||||
}
|
||||
|
||||
/// <summary>Hash of an image file; null when it is not a decodable image.</summary>
|
||||
public static ulong? ComputeFromFile(string path)
|
||||
{
|
||||
using var stream = File.OpenRead(path);
|
||||
return Compute(stream);
|
||||
}
|
||||
|
||||
/// <summary>Hash of a decoded bitmap (any size, premultiplied RGBA 8888 or convertible).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The hash of a 32×32 grey image (row-major).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Grey levels (0–255) of an RGBA premultiplied bitmap, composited over white.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Area-averaging resample with exact fractional coverage (no aliasing when reducing).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>For each target cell, the source cells it covers and their normalized weights.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
using System.Numerics;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>A library photo close to the searched one.</summary>
|
||||
public readonly record struct PerceptualHashMatch(long MediaId, long AccountId, ulong Hash, int Distance);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class PerceptualHashIndex
|
||||
{
|
||||
private readonly ReaderWriterLockSlim _lock = new(LockRecursionPolicy.NoRecursion);
|
||||
private readonly Dictionary<long, int> _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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Replaces the content with the hashes stored in the database.</summary>
|
||||
public void Load(IEnumerable<PerceptualHashRecord> 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Adds or replaces the hash of a file.</summary>
|
||||
public void Add(long mediaId, long accountId, ulong hash)
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
AddUnlocked(mediaId, accountId, hash);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Removes the hash of a file (deleted from the library).</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Files whose hash is within <paramref name="maxDistance"/> of <paramref name="hash"/>. With
|
||||
/// <paramref name="preferAccountId"/>, matches of that account come first (spec §9.3: «si cerca prima nell'account di
|
||||
/// destinazione, poi nel resto della libreria»); then by distance.
|
||||
/// </summary>
|
||||
public IReadOnlyList<PerceptualHashMatch> FindSimilar(
|
||||
ulong hash,
|
||||
int maxDistance = PerceptualHash.DuplicateThreshold,
|
||||
long? preferAccountId = null,
|
||||
long? excludeMediaId = null,
|
||||
int limit = 50)
|
||||
{
|
||||
var matches = new List<PerceptualHashMatch>();
|
||||
_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++;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
using System.Buffers;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>Size and SHA-256 of a file written by <see cref="SafeFileWriter"/>.</summary>
|
||||
public readonly record struct FileDigest(long Bytes, string Sha256);
|
||||
|
||||
/// <summary>A file safely written to its final name.</summary>
|
||||
/// <param name="RelativePath">Path relative to the root folder, '/' separated (may differ from the one asked: never overwrites).</param>
|
||||
/// <param name="FullPath">Full path on disk.</param>
|
||||
/// <param name="Bytes">Size.</param>
|
||||
/// <param name="Sha256">Lowercase hex SHA-256, computed while writing.</param>
|
||||
/// <param name="LastWriteTimeSet">The modification time was set as asked.</param>
|
||||
public sealed record SavedFile(string RelativePath, string FullPath, long Bytes, string Sha256, bool LastWriteTimeSet);
|
||||
|
||||
/// <summary>Options of a safe write.</summary>
|
||||
public sealed record SafeWriteOptions
|
||||
{
|
||||
/// <summary>Set the file modification time to this instant (publication time, spec §4.7). Null leaves it.</summary>
|
||||
public DateTimeOffset? LastWriteTime { get; init; }
|
||||
|
||||
/// <summary>Abort with <see cref="FileTooLargeException"/> beyond this size (e.g. «Salta i video oltre»).</summary>
|
||||
public long? MaxBytes { get; init; }
|
||||
|
||||
/// <summary>Bytes written so far.</summary>
|
||||
public IProgress<long>? Progress { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The content exceeded <see cref="SafeWriteOptions.MaxBytes"/>; nothing was kept.</summary>
|
||||
public sealed class FileTooLargeException : IOException
|
||||
{
|
||||
public FileTooLargeException()
|
||||
{
|
||||
}
|
||||
|
||||
public FileTooLargeException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public FileTooLargeException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes library files safely (spec §6.5 point 4, rule 12):
|
||||
/// <list type="number">
|
||||
/// <item>the content goes to a temporary name (<c>.febe-*.part</c>) in the destination folder;</item>
|
||||
/// <item>SHA-256 is computed while writing, then the data is flushed to disk;</item>
|
||||
/// <item>the file is renamed to its final name; an existing file is never overwritten — a free name
|
||||
/// («nome (2).jpg») is chosen instead;</item>
|
||||
/// <item>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.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathLength)
|
||||
{
|
||||
/// <summary>Prefix of temporary files.</summary>
|
||||
public const string TempPrefix = ".febe-";
|
||||
|
||||
/// <summary>Suffix of temporary files.</summary>
|
||||
public const string TempSuffix = ".part";
|
||||
|
||||
private const int BufferSize = 128 * 1024;
|
||||
private const int MaxNameAttempts = 10_000;
|
||||
|
||||
/// <summary>Serializes «is the name free? then rename» across all writers of the process.</summary>
|
||||
private static readonly Lock MoveGate = new();
|
||||
|
||||
/// <summary>Writes <paramref name="source"/> to <paramref name="relativePath"/> inside <paramref name="rootFolder"/>.</summary>
|
||||
public Task<SavedFile> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes <paramref name="source"/> and decides the final name only after hashing (e.g. profile pictures, named after
|
||||
/// their SHA-256). The temporary file is written in <paramref name="tempDirectory"/> (relative to the root, '/'
|
||||
/// separated; use the destination folder when known).
|
||||
/// </summary>
|
||||
public async Task<SavedFile> SaveAsync(
|
||||
Stream source,
|
||||
string rootFolder,
|
||||
string tempDirectory,
|
||||
Func<FileDigest, string> relativePathFor,
|
||||
SafeWriteOptions? options = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(relativePathFor);
|
||||
var saved = await SaveAsync(source, rootFolder, tempDirectory, (d, _) => ValueTask.FromResult<string?>(relativePathFor(d)), options, ct)
|
||||
.ConfigureAwait(false);
|
||||
return saved!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes <paramref name="source"/> to a temporary file, then asks <paramref name="decide"/> — knowing size and
|
||||
/// SHA-256 — for the final relative path. When <paramref name="decide"/> 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.
|
||||
/// </summary>
|
||||
public async Task<SavedFile?> SaveAsync(
|
||||
Stream source,
|
||||
string rootFolder,
|
||||
string tempDirectory,
|
||||
Func<FileDigest, CancellationToken, ValueTask<string?>> 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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes temporary files left by an interrupted process (never library files: only <c>.febe-*.part</c>).
|
||||
/// Returns how many were removed.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>True for a temporary file name of the safe writer.</summary>
|
||||
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<FileDigest> WriteTempAsync(Stream source, string tempPath, SafeWriteOptions options, CancellationToken ct)
|
||||
{
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
var buffer = ArrayPool<byte>.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<byte>.Shared.Return(buffer);
|
||||
}
|
||||
|
||||
return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
|
||||
}
|
||||
|
||||
/// <summary>Sanitized segments of a relative path ('/' or '\' separated). «..» becomes «_»: nothing escapes the root.</summary>
|
||||
private static List<string> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Text indexed for an entry: caption and author.</summary>
|
||||
public static string ForEntry(string? caption, string? author) =>
|
||||
Normalize(string.Join(' ', new[] { caption, author }.Where(s => !string.IsNullOrWhiteSpace(s))));
|
||||
|
||||
/// <summary>A LIKE pattern «%term%» with %, _ and \ escaped (use with ESCAPE '\').</summary>
|
||||
public static string LikePattern(string normalizedTerm)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(normalizedTerm);
|
||||
var escaped = normalizedTerm.Replace("\\", "\\\\", StringComparison.Ordinal)
|
||||
.Replace("%", "\\%", StringComparison.Ordinal)
|
||||
.Replace("_", "\\_", StringComparison.Ordinal);
|
||||
return "%" + escaped + "%";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using SkiaSharp;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// Thumbnails of the library (spec §8.4): 480 pixels on the long side, JPEG, generated once and kept under
|
||||
/// <c>Dati/miniature</c>, 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 (<see cref="VideoFrameExtractor"/>); without either, the interface shows the neutral tile
|
||||
/// (<see cref="NeutralVideoTile"/>).
|
||||
/// </summary>
|
||||
public sealed class ThumbnailStore
|
||||
{
|
||||
/// <summary>Long side of a thumbnail, in pixels.</summary>
|
||||
public const int LongSide = 480;
|
||||
|
||||
/// <summary>JPEG quality of thumbnails.</summary>
|
||||
public const int JpegQuality = 82;
|
||||
|
||||
/// <summary>File name of the neutral tile for videos without a cover.</summary>
|
||||
public const string NeutralVideoTileName = "_video.jpg";
|
||||
|
||||
private readonly string _root;
|
||||
|
||||
public ThumbnailStore(string thumbnailsFolder)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(thumbnailsFolder);
|
||||
_root = Path.GetFullPath(thumbnailsFolder);
|
||||
}
|
||||
|
||||
/// <summary>The thumbnails folder.</summary>
|
||||
public string Root => _root;
|
||||
|
||||
/// <summary>Path of the thumbnail of a key (lowercase hex SHA-256).</summary>
|
||||
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));
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Creates the thumbnail of an image file.</summary>
|
||||
public bool CreateFromFile(string key, string imagePath)
|
||||
{
|
||||
using var stream = File.OpenRead(imagePath);
|
||||
return Create(key, stream);
|
||||
}
|
||||
|
||||
/// <summary>Removes a thumbnail (when no file of the library uses its key any more).</summary>
|
||||
public bool Delete(string key)
|
||||
{
|
||||
var path = PathFor(key);
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
File.Delete(path);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The neutral tile for videos without a cover, created on first use (grey, with a play sign).</summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class VideoFrameExtractor
|
||||
{
|
||||
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30);
|
||||
|
||||
private VideoFrameExtractor(string executable) => Executable = executable;
|
||||
|
||||
/// <summary>Full path of ffmpeg.</summary>
|
||||
public string Executable { get; }
|
||||
|
||||
/// <summary>Finds ffmpeg on the PATH (or at <paramref name="explicitPath"/>); null when it is not available.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A JPEG frame of the video, taken one second in (or the first frame of shorter videos); null when ffmpeg cannot
|
||||
/// read the file.
|
||||
/// </summary>
|
||||
public async Task<byte[]?> 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<byte[]?> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// <list type="bullet">
|
||||
/// <item>forbidden characters <c>< > : " / \ | ? *</c> and control characters become <c>_</c>;</item>
|
||||
/// <item>reserved device names (CON, PRN, AUX, NUL, COM0–9, LPT0–9, COM¹²³, LPT¹²³, CONIN$, CONOUT$), also with an
|
||||
/// extension, get a <c>_</c> after the base name;</item>
|
||||
/// <item>trailing dots and spaces are removed (so <c>.</c> and <c>..</c> can never appear);</item>
|
||||
/// <item>a segment is at most 255 characters; a whole path at most <see cref="MaxPathLength"/>.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public static class WindowsFileNames
|
||||
{
|
||||
/// <summary>Total path length kept below the classic Windows limit of 260 (spec §4.7: «percorsi oltre 240 caratteri»).</summary>
|
||||
public const int MaxPathLength = 240;
|
||||
|
||||
/// <summary>Maximum length of one path segment on NTFS.</summary>
|
||||
public const int MaxSegmentLength = 255;
|
||||
|
||||
/// <summary>Replacement for forbidden characters.</summary>
|
||||
public const char Replacement = '_';
|
||||
|
||||
/// <summary>Length of the hash suffix added to shortened names (<c>~</c> plus 8 hex digits).</summary>
|
||||
private const int HashSuffixLength = 9;
|
||||
|
||||
/// <summary>Shortest stem kept when shortening a name, before giving up.</summary>
|
||||
private const int MinimumStem = 8;
|
||||
|
||||
private static readonly HashSet<string> 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³",
|
||||
};
|
||||
|
||||
/// <summary>True for a character Windows does not accept in a file name.</summary>
|
||||
public static bool IsForbidden(char ch) => ch < 0x20 || ch is '<' or '>' or ':' or '"' or '/' or '\\' or '|' or '?' or '*';
|
||||
|
||||
/// <summary>True when the segment names a reserved device (with or without extension).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes one path segment (a folder or file name) valid on Windows. Idempotent. Never returns an empty string,
|
||||
/// <c>.</c> or <c>..</c>.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fits a relative path (already sanitized segments, the last one a file name) under <paramref name="baseFolder"/>
|
||||
/// so that the full path is at most <paramref name="maxLength"/> characters. The file name is shortened first,
|
||||
/// keeping its extension; then the longest folder segments. A shortened part ends with <c>~</c> and eight hex digits
|
||||
/// of the SHA-256 of the original, so different names stay different (for example <c>_1</c> and <c>_2</c>).
|
||||
/// </summary>
|
||||
/// <exception cref="PathTooLongException">Even shortened, the path does not fit (the base folder is too long).</exception>
|
||||
public static IReadOnlyList<string> FitPath(string baseFolder, IReadOnlyList<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>Splits «name.ext» into («name», «.ext»). Names starting with a dot have no extension.</summary>
|
||||
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..]);
|
||||
}
|
||||
|
||||
/// <summary>Shortens a name to at most <paramref name="maxLength"/> characters with a hash suffix of the original.</summary>
|
||||
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('.', ' ');
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Storage;
|
||||
|
||||
/// <summary>Accounts (spec §4.2, §8.3 <c>account</c>).</summary>
|
||||
public interface IAccountStore
|
||||
{
|
||||
Task<Account?> GetAsync(long accountId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The account with this Instagram identifier: the identity of an account.</summary>
|
||||
Task<Account?> FindByInstagramIdAsync(string instagramId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Case-insensitive lookup by current user name.</summary>
|
||||
Task<Account?> FindByUsernameAsync(string username, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Alberto's own profile («Tu»), when known.</summary>
|
||||
Task<Account?> GetMineAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>All accounts, ordered by user name.</summary>
|
||||
Task<IReadOnlyList<Account>> ListAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>All accounts with their counts; «new» counts are entries discovered at or after <paramref name="newSince"/>.</summary>
|
||||
Task<IReadOnlyList<AccountSummary>> ListSummariesAsync(DateTimeOffset newSince, CancellationToken ct = default);
|
||||
|
||||
Task<AccountStats> GetStatsAsync(long accountId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Adds an account and returns it with its key.</summary>
|
||||
/// <exception cref="DuplicateRecordException">Another account has the same Instagram identifier, or is already «Tu».</exception>
|
||||
Task<Account> AddAsync(Account account, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Replaces every field of an existing account (settings screen).</summary>
|
||||
Task UpdateAsync(Account account, CancellationToken ct = default);
|
||||
|
||||
Task SetStateAsync(long accountId, AccountState state, DateTimeOffset at, UnreachableReason? reason = null, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Updates last and next check times. Null values leave the stored value unchanged.</summary>
|
||||
Task UpdateChecksAsync(long accountId, AccountCheckTimes times, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Stores the backfill resume point; <paramref name="completedAt"/> marks the backfill as finished.</summary>
|
||||
Task SetBackfillAsync(long accountId, string? cursor, DateTimeOffset? completedAt, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
Task RenameAsync(long accountId, string newUsername, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Adds notices (e.g. unrecognized format) to an account.</summary>
|
||||
Task AddNoticesAsync(long accountId, AccountNotices notices, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Clears notices once Alberto has seen them.</summary>
|
||||
Task ClearNoticesAsync(long accountId, AccountNotices notices, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
Task DeleteAsync(long accountId, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Check times of an account; null values are left unchanged.</summary>
|
||||
public sealed record AccountCheckTimes
|
||||
{
|
||||
public DateTimeOffset? LastProfileCheckAt { get; init; }
|
||||
|
||||
public DateTimeOffset? NextProfileCheckAt { get; init; }
|
||||
|
||||
public DateTimeOffset? LastStoriesCheckAt { get; init; }
|
||||
|
||||
public DateTimeOffset? NextStoriesCheckAt { get; init; }
|
||||
|
||||
/// <summary>Profile facts read with the check (null: unchanged).</summary>
|
||||
public int? PostCount { get; init; }
|
||||
|
||||
public bool? IsPrivate { get; init; }
|
||||
|
||||
public bool? IsFollowed { get; init; }
|
||||
|
||||
public string? DisplayName { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A unique constraint refused a record (duplicate Instagram identifier, second «Tu», ...).</summary>
|
||||
public sealed class DuplicateRecordException : Exception
|
||||
{
|
||||
public DuplicateRecordException()
|
||||
{
|
||||
}
|
||||
|
||||
public DuplicateRecordException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public DuplicateRecordException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Storage;
|
||||
|
||||
/// <summary>Probable duplicates waiting for Alberto (spec §8.3 <c>duplicate_pair</c>, §9.3, §9.5).</summary>
|
||||
public interface IDuplicateStore
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds a pair. Idempotent: if the same pending pair (same sides) exists, it is returned unchanged.
|
||||
/// </summary>
|
||||
Task<DuplicatePair> AddAsync(DuplicatePair pair, CancellationToken ct = default);
|
||||
|
||||
Task<DuplicatePair?> GetAsync(long pairId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Pending pairs in creation order, after <paramref name="afterId"/>.</summary>
|
||||
Task<IReadOnlyList<DuplicatePair>> ListPendingAsync(DuplicateOrigin? origin = null, long afterId = 0, int limit = 200, CancellationToken ct = default);
|
||||
|
||||
Task<int> CountPendingAsync(DuplicateOrigin? origin = null, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Records Alberto's decision. Applying it to files is the caller's job.</summary>
|
||||
Task DecideAsync(long pairId, DuplicateDecision decision, DateTimeOffset at, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Storage;
|
||||
|
||||
/// <summary>The engine queue (spec §8.3 <c>task</c>). Persisted: a restart resets nothing.</summary>
|
||||
public interface ITaskStore
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
Task<EngineTask> EnqueueAsync(EngineTask task, CancellationToken ct = default);
|
||||
|
||||
Task<EngineTask?> GetAsync(long taskId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Pending tasks due at <paramref name="now"/>: highest priority first, then earliest due, then oldest.</summary>
|
||||
Task<IReadOnlyList<EngineTask>> PeekDueAsync(DateTimeOffset now, int limit, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Pending tasks by due time (the queue shown in Attività, «verso le»).</summary>
|
||||
Task<IReadOnlyList<EngineTask>> ListPendingAsync(int limit, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Pending → Running, atomically. False if the task was not pending any more.</summary>
|
||||
Task<bool> TryStartAsync(long taskId, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Running → Done.</summary>
|
||||
Task CompleteAsync(long taskId, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Records a failure: with <paramref name="retryAt"/> the task goes back to pending at that time, otherwise it
|
||||
/// becomes Failed. Attempts are incremented.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>Cancels every pending task of an account. Returns how many.</summary>
|
||||
Task<int> CancelForAccountAsync(long accountId, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>At start-up: tasks left running by a previous process go back to pending. Returns how many.</summary>
|
||||
Task<int> RequeueRunningAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Deletes finished tasks (done, failed, cancelled) completed before <paramref name="before"/>.</summary>
|
||||
Task<int> PurgeFinishedAsync(DateTimeOffset before, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Counted actions toward the site (spec §7.4 <c>action_log</c>): the budgets are computed from here, not in memory.</summary>
|
||||
public interface IActionLogStore
|
||||
{
|
||||
Task<ActionLogRecord> AppendAsync(ActionLogRecord record, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Sum of amounts of a category in [from, to), optionally for one account.</summary>
|
||||
Task<long> SumAsync(ActionKind category, DateTimeOffset from, DateTimeOffset to, long? accountId = null, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Usage of every category: the rolling window (now − 60 min, now] and the local calendar day of
|
||||
/// <paramref name="now"/> in <paramref name="zone"/>. Categories without actions are included with zero.
|
||||
/// </summary>
|
||||
Task<IReadOnlyDictionary<ActionKind, BudgetUsage>> GetUsageAsync(DateTimeOffset now, TimeZoneInfo zone, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Time of the last action (of a category, or of any category except data downloads when null).</summary>
|
||||
Task<DateTimeOffset?> GetLastActionAtAsync(ActionKind? category = null, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Actions in [from, to), oldest first.</summary>
|
||||
Task<IReadOnlyList<ActionLogRecord>> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Deletes actions older than <paramref name="before"/>. Keep at least two days for the daily budgets.</summary>
|
||||
Task<int> PruneAsync(DateTimeOffset before, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Engine sessions (spec §8.3 <c>session</c>).</summary>
|
||||
public interface ISessionStore
|
||||
{
|
||||
Task<SessionRecord> StartAsync(DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
Task EndAsync(long sessionId, DateTimeOffset at, SessionOutcome outcome, int actionCount, string? summary = null, CancellationToken ct = default);
|
||||
|
||||
Task<SessionRecord?> GetAsync(long sessionId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The most recently started session.</summary>
|
||||
Task<SessionRecord?> GetLastAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Sessions overlapping [from, to), by start time (strip of the day).</summary>
|
||||
Task<IReadOnlyList<SessionRecord>> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default);
|
||||
|
||||
/// <summary>At start-up: sessions left open become Interrupted, ended at <paramref name="at"/>. Returns how many.</summary>
|
||||
Task<int> CloseInterruptedAsync(DateTimeOffset at, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Stops of the circuit breaker (spec §7.6, §8.3 <c>incident</c>).</summary>
|
||||
public interface IIncidentStore
|
||||
{
|
||||
/// <summary>Opens an incident and returns it with its key.</summary>
|
||||
Task<Incident> OpenAsync(Incident incident, CancellationToken ct = default);
|
||||
|
||||
Task ResolveAsync(long incidentId, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
Task<Incident?> GetAsync(long incidentId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Unresolved incidents, oldest first.</summary>
|
||||
Task<IReadOnlyList<Incident>> ListOpenAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Incidents that started in [from, to), oldest first.</summary>
|
||||
Task<IReadOnlyList<Incident>> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Incidents of a level since an instant («tre rallentamenti in sette giorni»; «la seconda nelle 24 ore»).</summary>
|
||||
Task<int> CountAsync(SignalLevel level, DateTimeOffset since, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>The readable timeline (spec §8.3 <c>event</c>).</summary>
|
||||
public interface IEventStore
|
||||
{
|
||||
Task<EventRecord> AppendAsync(EventRecord record, CancellationToken ct = default);
|
||||
|
||||
/// <summary>A page of the timeline, newest first.</summary>
|
||||
Task<IReadOnlyList<EventRecord>> ListAsync(EventQuery query, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Events after a known one, oldest first: incremental updates of the interface.</summary>
|
||||
Task<IReadOnlyList<EventRecord>> ListAfterAsync(long afterId, int limit = 200, CancellationToken ct = default);
|
||||
|
||||
Task<int> PruneAsync(DateTimeOffset before, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>A page of the timeline: newest first, before <see cref="BeforeId"/> when given.</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>Local copy of the list of profiles Alberto follows (spec §4.2, §8.3 <c>following</c>).</summary>
|
||||
public interface IFollowingStore
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
Task UpsertAsync(IReadOnlyList<FollowingRecord> records, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The list in reading order.</summary>
|
||||
Task<IReadOnlyList<FollowingRecord>> ListAsync(CancellationToken ct = default);
|
||||
|
||||
Task<int> CountAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>When the most recent profile was read.</summary>
|
||||
Task<DateTimeOffset?> GetLastReadAtAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>After a complete re-read started at <paramref name="readStartedAt"/>: removes profiles not seen (unfollowed).</summary>
|
||||
Task<int> RemoveNotReadSinceAsync(DateTimeOffset readStartedAt, CancellationToken ct = default);
|
||||
|
||||
Task ClearAsync(CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Storage;
|
||||
|
||||
/// <summary>Entries (spec §4.3, §8.3 <c>entry</c>) and the library queries of the interface (spec §4.6).</summary>
|
||||
public interface IEntryStore
|
||||
{
|
||||
Task<Entry?> GetAsync(long entryId, CancellationToken ct = default);
|
||||
|
||||
Task<EntryWithMedia?> GetWithMediaAsync(long entryId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The entry with this identity, in any state (deleted included).</summary>
|
||||
Task<Entry?> FindAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «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).
|
||||
/// </summary>
|
||||
Task<bool> IsKnownAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Which of these identifiers are already known for (account, kind), in any state. For readers: one query per page.</summary>
|
||||
Task<IReadOnlySet<string>> GetKnownInstagramIdsAsync(long accountId, EntryKind kind, IReadOnlyCollection<string> instagramIds, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Entries of an account with this Instagram identifier, any kind and state (e.g. a story that entered a highlight).</summary>
|
||||
Task<IReadOnlyList<Entry>> FindByInstagramIdAsync(long accountId, string instagramId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// An entry of (account, kind) published within <paramref name="tolerance"/> of <paramref name="publishedAt"/>:
|
||||
/// recognizes imported entries that have no Instagram identifier (spec §9.5, two seconds).
|
||||
/// </summary>
|
||||
Task<Entry?> FindByPublicationTimeAsync(long accountId, EntryKind kind, DateTimeOffset publishedAt, TimeSpan tolerance, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>Created = false</c>.
|
||||
/// Positions of the files must be distinct.
|
||||
/// </summary>
|
||||
Task<AddEntryResult> AddAsync(Entry entry, IReadOnlyList<Media> media, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Adds many entries in one transaction (import, rebuild). Same semantics as <see cref="AddAsync"/>.</summary>
|
||||
Task<IReadOnlyList<AddEntryResult>> AddManyAsync(IReadOnlyList<NewEntry> entries, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Replaces the mutable fields of an entry (Instagram identifier, code, caption, author, state, dates).</summary>
|
||||
Task UpdateAsync(Entry entry, CancellationToken ct = default);
|
||||
|
||||
Task SetStateAsync(long entryId, EntryState state, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Recomputes the state of an entry from its files (<see cref="EntryStateRules.FromMedia"/>).</summary>
|
||||
Task<EntryState> RecomputeStateAsync(long entryId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «Eliminato»: the entry stays without files so it is not downloaded again (spec §4.6). Its files become
|
||||
/// <see cref="MediaState.Deleted"/> and lose their path and perceptual hash; SHA-256 and size are kept. Deleting files on disk is the caller's job.
|
||||
/// </summary>
|
||||
Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>«Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade).</summary>
|
||||
Task RemoveAsync(long entryId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Entries of an account ordered by publication time, newest first (account tabs, collection pipeline).</summary>
|
||||
Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Entries of (account, kind) discovered in [from, to): per-account daily backfill limit.</summary>
|
||||
Task<int> CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default);
|
||||
|
||||
/// <summary>A window of the library mosaic with keyset paging: stays fast over 200,000 entries.</summary>
|
||||
Task<LibraryPage> QueryLibraryAsync(LibraryQuery query, CancellationToken ct = default);
|
||||
|
||||
Task<LibraryTotals> GetLibraryTotalsAsync(LibraryFilter filter, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Entries per local calendar day in Alberto's zone, newest day first.</summary>
|
||||
Task<IReadOnlyList<DayCount>> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Tiles for given entries, in the given order (e.g. the items of a highlight collection).</summary>
|
||||
Task<IReadOnlyList<LibraryTile>> GetTilesAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
namespace Febe.Core.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Everything Febe keeps in its database, as one object (implemented by <c>Febe.Data.FebeDatabase</c>).
|
||||
/// Writes are serialized by a single writer; reads run concurrently.
|
||||
/// </summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>Maintenance of the database file.</summary>
|
||||
public interface IDatabaseMaintenance
|
||||
{
|
||||
/// <summary>Full path of the database file.</summary>
|
||||
string DatabasePath { get; }
|
||||
|
||||
/// <summary>Schema version (PRAGMA user_version).</summary>
|
||||
int SchemaVersion { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Writes a consistent copy of the database to a new file with <c>VACUUM INTO</c> (spec §8.5).
|
||||
/// The destination must not exist.
|
||||
/// </summary>
|
||||
Task BackupToAsync(string destinationFile, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Runs <c>PRAGMA quick_check</c>; true when the database is sound.</summary>
|
||||
Task<bool> CheckIntegrityAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Lets SQLite refresh its statistics (<c>PRAGMA optimize</c>).</summary>
|
||||
Task OptimizeAsync(CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Storage;
|
||||
|
||||
/// <summary>Highlight collections and their ordered contents (spec §8.3 <c>highlight</c>, <c>highlight_entry</c>).</summary>
|
||||
public interface IHighlightStore
|
||||
{
|
||||
Task<Highlight?> GetAsync(long highlightId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Collections of an account in profile order.</summary>
|
||||
Task<IReadOnlyList<Highlight>> ListAsync(long accountId, bool includeRemoved = false, CancellationToken ct = default);
|
||||
|
||||
Task<Highlight?> FindAsync(long accountId, string instagramId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Lookup by title, for collections known only from an import or a rebuild.</summary>
|
||||
Task<Highlight?> FindByTitleAsync(long accountId, string title, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Adds or updates a collection. Matches an existing one by key, then by (account, Instagram identifier).
|
||||
/// Returns the stored collection.
|
||||
/// </summary>
|
||||
Task<Highlight> UpsertAsync(Highlight highlight, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Sets the profile order of the given collections (positions 0, 1, ...).</summary>
|
||||
Task SetOrderAsync(long accountId, IReadOnlyList<long> highlightIdsInOrder, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The collection disappeared from the profile; its contents and files stay.</summary>
|
||||
Task MarkRemovedAsync(long highlightId, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Contents of a collection in order.</summary>
|
||||
Task<IReadOnlyList<HighlightItem>> ListItemsAsync(long highlightId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Replaces the contents of a collection with these entries, in this order.</summary>
|
||||
Task SetItemsAsync(long highlightId, IReadOnlyList<long> entryIdsInOrder, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Appends an entry at the end of a collection if it is not there yet.</summary>
|
||||
Task AddItemAsync(long highlightId, long entryId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Collections that contain an entry (an entry may be in several).</summary>
|
||||
Task<IReadOnlyList<Highlight>> ListForEntryAsync(long entryId, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Storage;
|
||||
|
||||
/// <summary>Imports and their files (spec §8.3 <c>import_run</c>, <c>import_file</c>; §9).</summary>
|
||||
public interface IImportStore
|
||||
{
|
||||
Task<ImportRun> CreateRunAsync(ImportRun run, CancellationToken ct = default);
|
||||
|
||||
Task UpdateRunAsync(ImportRun run, CancellationToken ct = default);
|
||||
|
||||
Task<ImportRun?> GetRunAsync(long runId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Imports, newest first.</summary>
|
||||
Task<IReadOnlyList<ImportRun>> ListRunsAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Adds files to an import in one transaction. Files already recorded for the same relative path are left
|
||||
/// unchanged (so an interrupted analysis resumes).
|
||||
/// </summary>
|
||||
Task AddFilesAsync(IReadOnlyList<ImportFile> files, CancellationToken ct = default);
|
||||
|
||||
Task UpdateFileAsync(ImportFile file, CancellationToken ct = default);
|
||||
|
||||
Task UpdateFilesAsync(IReadOnlyList<ImportFile> files, CancellationToken ct = default);
|
||||
|
||||
Task<ImportFile?> GetFileAsync(long fileId, CancellationToken ct = default);
|
||||
|
||||
Task<ImportFile?> FindFileAsync(long runId, string relativePath, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Files of an import, by key, with optional filters.</summary>
|
||||
Task<IReadOnlyList<ImportFile>> ListFilesAsync(ImportFileQuery query, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Files of the same import with this SHA-256 (duplicates inside the source).</summary>
|
||||
Task<IReadOnlyList<ImportFile>> FindFilesBySha256Async(long runId, string sha256, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Counts by outcome and by state.</summary>
|
||||
Task<ImportSummary> GetSummaryAsync(long runId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Source folders with their counts and association (review, mockup 09).</summary>
|
||||
Task<IReadOnlyList<ImportFolder>> ListFoldersAsync(long runId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Associates every file of a source folder with an account (null: not associated).</summary>
|
||||
Task SetFolderTargetAsync(long runId, string folder, long? accountId, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Filters for the files of an import.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Counts of an import.</summary>
|
||||
public sealed record ImportSummary(
|
||||
int Total,
|
||||
IReadOnlyDictionary<ImportOutcome, int> ByOutcome,
|
||||
IReadOnlyDictionary<ImportFileState, int> ByState,
|
||||
long Bytes);
|
||||
|
||||
/// <summary>A source folder of an import.</summary>
|
||||
public sealed record ImportFolder(string Folder, int Files, string? ProbableAccount, long? TargetAccountId);
|
||||
@@ -0,0 +1,52 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Storage;
|
||||
|
||||
/// <summary>Files of entries (spec §8.3 <c>media</c>), hashes and the download queue.</summary>
|
||||
public interface IMediaStore
|
||||
{
|
||||
Task<Media?> GetAsync(long mediaId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Files of an entry in position order.</summary>
|
||||
Task<IReadOnlyList<Media>> ListByEntryAsync(long entryId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<MediaLocation>> FindBySha256Async(string sha256, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
Task<IReadOnlyDictionary<string, long>> MapPathsAsync(long accountId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Perceptual hashes of the photos present in the library, to load the in-memory index.</summary>
|
||||
Task<IReadOnlyList<PerceptualHashRecord>> LoadPerceptualHashesAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Files waiting to be downloaded, in queue order: stories first (they expire), then by expiry and discovery.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Files waiting to be downloaded, for one account or overall («lo storico non corre più veloce dei download»).</summary>
|
||||
Task<int> CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Records a file now on disk and recomputes the state of its entry, in one transaction.</summary>
|
||||
Task MarkStoredAsync(long mediaId, StoredFile file, MediaState state, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Records a failed attempt: <paramref name="state"/> is Failed, Expired (address expired) or Skipped (a limit).
|
||||
/// Increments attempts and recomputes the state of the entry.
|
||||
/// </summary>
|
||||
Task MarkFailedAsync(long mediaId, MediaState state, string? error, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>A fresh address read from the page: the file goes back to «da scaricare».</summary>
|
||||
Task UpdateSourceAsync(long mediaId, string? sourceUrl, string? coverUrl, DateTimeOffset seenAt, CancellationToken ct = default);
|
||||
|
||||
Task SetThumbnailAsync(long mediaId, bool hasThumbnail, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Replaces every field of a file record.</summary>
|
||||
Task UpdateAsync(Media media, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Febe.Core.Storage;
|
||||
|
||||
/// <summary>Key-value settings (spec §8.3 <c>setting</c>). Keys are listed in <see cref="SettingKeys"/>.</summary>
|
||||
public interface ISettingsStore
|
||||
{
|
||||
Task<string?> GetAsync(string key, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Stores a value; null removes the key.</summary>
|
||||
Task SetAsync(string key, string? value, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Stores several values in one transaction; null values remove their key.</summary>
|
||||
Task SetManyAsync(IReadOnlyDictionary<string, string?> values, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyDictionary<string, string>> GetAllAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Known setting keys. Values are invariant-culture text.</summary>
|
||||
public static class SettingKeys
|
||||
{
|
||||
/// <summary>Library folder (spec §4.7 «Libreria»).</summary>
|
||||
public const string LibraryRoot = "libreria.cartella";
|
||||
|
||||
/// <summary>General naming scheme.</summary>
|
||||
public const string NamingScheme = "libreria.schema";
|
||||
|
||||
/// <summary>Naming scheme for highlight collections.</summary>
|
||||
public const string HighlightNamingScheme = "libreria.schema-evidenza";
|
||||
|
||||
/// <summary>«Imposta la data del file a quella di pubblicazione» (true/false).</summary>
|
||||
public const string SetFileTimeToPublication = "libreria.data-file-pubblicazione";
|
||||
}
|
||||
|
||||
/// <summary>Typed helpers over <see cref="ISettingsStore"/>.</summary>
|
||||
public static class SettingsStoreExtensions
|
||||
{
|
||||
public static async Task<bool> 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<long?> 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Storage;
|
||||
|
||||
/// <summary>Kind filter of the library (mockup 01): «Foto» and «Video» concern posts; the others have their own entry.</summary>
|
||||
public enum LibraryKindFilter
|
||||
{
|
||||
/// <summary>«Tutto»: posts, stories, highlights and tagged posts. Profile pictures are not in the library (spec §4.3).</summary>
|
||||
All,
|
||||
|
||||
/// <summary>«Foto»: posts with at least one photo.</summary>
|
||||
Photos,
|
||||
|
||||
/// <summary>«Video»: posts with at least one video (reels included).</summary>
|
||||
Videos,
|
||||
|
||||
/// <summary>«Storie».</summary>
|
||||
Stories,
|
||||
|
||||
/// <summary>«In evidenza»: highlight items, including stories referenced by a collection.</summary>
|
||||
Highlights,
|
||||
|
||||
/// <summary>«Taggati».</summary>
|
||||
Tagged,
|
||||
|
||||
/// <summary>Profile pictures: the «Profilo» tab of an account.</summary>
|
||||
ProfilePictures,
|
||||
|
||||
/// <summary>Posts of any media (the «Post» tab of an account).</summary>
|
||||
Posts,
|
||||
}
|
||||
|
||||
/// <summary>Filters of the library mosaic and of the account tabs (spec §4.6).</summary>
|
||||
public sealed record LibraryFilter
|
||||
{
|
||||
public LibraryKindFilter Kind { get; init; } = LibraryKindFilter.All;
|
||||
|
||||
/// <summary>Only these accounts (null: all).</summary>
|
||||
public IReadOnlyList<long>? AccountIds { get; init; }
|
||||
|
||||
/// <summary>Published at or after (UTC).</summary>
|
||||
public DateTimeOffset? From { get; init; }
|
||||
|
||||
/// <summary>Published before (UTC).</summary>
|
||||
public DateTimeOffset? To { get; init; }
|
||||
|
||||
/// <summary>«Provenienza»: downloaded or imported (null: both).</summary>
|
||||
public Provenance? Provenance { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Search by account name (user name or display name) and caption text. Case and accents are ignored.
|
||||
/// </summary>
|
||||
public string? Search { get; init; }
|
||||
|
||||
/// <summary>Entry states shown. Null means <see cref="EntryStateRules.Visible"/> (entries with files).</summary>
|
||||
public IReadOnlyList<EntryState>? States { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Keyset position in the library order (publication time descending, then id descending).</summary>
|
||||
public readonly record struct LibraryCursor(DateTimeOffset PublishedAt, long EntryId)
|
||||
{
|
||||
/// <summary>A cursor that starts the older direction at a given instant (to jump to a date).</summary>
|
||||
public static LibraryCursor At(DateTimeOffset instant) => new(instant, long.MaxValue);
|
||||
}
|
||||
|
||||
public enum LibraryDirection
|
||||
{
|
||||
/// <summary>Entries published before the cursor (scrolling down).</summary>
|
||||
Older,
|
||||
|
||||
/// <summary>Entries published after the cursor (scrolling up, or new entries arriving on top).</summary>
|
||||
Newer,
|
||||
}
|
||||
|
||||
/// <summary>A window of the library. Without a cursor the window starts from the newest entry.</summary>
|
||||
public sealed record LibraryQuery
|
||||
{
|
||||
public LibraryFilter Filter { get; init; } = new();
|
||||
|
||||
public LibraryCursor? Cursor { get; init; }
|
||||
|
||||
public LibraryDirection Direction { get; init; } = LibraryDirection.Older;
|
||||
|
||||
/// <summary>Maximum tiles (1–1000).</summary>
|
||||
public int Limit { get; init; } = 200;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One tile of the mosaic: an entry with its cover file (the file at the lowest position).
|
||||
/// <see cref="CoverSha256"/> is the thumbnail key.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// A window of tiles, always in display order (newest first). <see cref="Older"/> and <see cref="Newer"/> continue
|
||||
/// the window in each direction; null means there is nothing more that way.
|
||||
/// </summary>
|
||||
public sealed record LibraryPage(IReadOnlyList<LibraryTile> Tiles, LibraryCursor? Older, LibraryCursor? Newer);
|
||||
|
||||
/// <summary>Number of entries of a local calendar day (headers of the mosaic, «14 nuovi elementi»).</summary>
|
||||
public readonly record struct DayCount(DateOnly Day, int Count);
|
||||
|
||||
/// <summary>Totals for the title of the library («48.212 elementi di 38 account»).</summary>
|
||||
public readonly record struct LibraryTotals(int Entries, int Accounts);
|
||||
|
||||
/// <summary>Options of a per-account list of entries.</summary>
|
||||
public sealed record EntryListOptions
|
||||
{
|
||||
/// <summary>Only this kind (null: all).</summary>
|
||||
public EntryKind? Kind { get; init; }
|
||||
|
||||
/// <summary>Only these states (null: all, deleted included).</summary>
|
||||
public IReadOnlyList<EntryState>? States { get; init; }
|
||||
|
||||
/// <summary>Continue after this cursor (publication time descending).</summary>
|
||||
public LibraryCursor? Before { get; init; }
|
||||
|
||||
public int Limit { get; init; } = 200;
|
||||
}
|
||||
|
||||
/// <summary>Counts of an account (header of the account card, mockup 05; list of mockup 03).</summary>
|
||||
public sealed record AccountStats
|
||||
{
|
||||
public long AccountId { get; init; }
|
||||
|
||||
/// <summary>Entries in the library (with files), all kinds except profile pictures.</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>Highlight collections on the profile (not removed).</summary>
|
||||
public int HighlightCollections { get; init; }
|
||||
|
||||
/// <summary>Bytes of the files present.</summary>
|
||||
public long Bytes { get; init; }
|
||||
|
||||
/// <summary>Files still to download.</summary>
|
||||
public int PendingFiles { get; init; }
|
||||
|
||||
public DateTimeOffset? LastPublishedAt { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>An account with its counts, for the accounts list.</summary>
|
||||
/// <param name="Account">The account.</param>
|
||||
/// <param name="EntriesInLibrary">«In libreria».</param>
|
||||
/// <param name="Posts">Posts in the library (backfill progress: «340 di 1.280 post»).</param>
|
||||
/// <param name="NewPostsSince">Posts discovered since the given instant («1 nuovo post oggi»).</param>
|
||||
/// <param name="NewStoriesSince">Stories discovered since the given instant («2 nuove storie oggi»).</param>
|
||||
public sealed record AccountSummary(Account Account, int EntriesInLibrary, int Posts, int NewPostsSince, int NewStoriesSince);
|
||||
|
||||
/// <summary>A perceptual hash of a library file, to load the in-memory index.</summary>
|
||||
public readonly record struct PerceptualHashRecord(long MediaId, long AccountId, ulong Hash);
|
||||
|
||||
/// <summary>Result of adding an entry: the stored entry and whether it was new.</summary>
|
||||
public sealed record AddEntryResult(EntryWithMedia Stored, bool Created);
|
||||
|
||||
/// <summary>An entry to add with its files.</summary>
|
||||
public sealed record NewEntry(Entry Entry, IReadOnlyList<Media> Media);
|
||||
Reference in new issue
Block a user