Interfaccia, parte 2: Attività, Impostazioni, collegamento, Importa, doppioni, primo avvio ed errori di configurazione

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

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 20:27:34 +00:00
1 parent 0515776b04
commit d614050ee5
90 files changed
+7825 -49

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
using Febe.Core.Storage;
namespace Febe.Core.Alerts;
/// <summary>The events that deserve an alert (spec §13.3). The red strip in the interface is always on.</summary>
/// <param name="Verification">«Verifica richiesta».</param>
/// <param name="Disconnection">«Disconnessione».</param>
/// <param name="Throttle">«Fermo per rallentamento e ripresa».</param>
/// <param name="BackfillDone">«Storico di un account completato».</param>
/// <param name="DiskLow">«Disco quasi pieno».</param>
/// <param name="UnknownFormat">«Formato non riconosciuto».</param>
public sealed record AlertEvents(bool Verification, bool Disconnection, bool Throttle, bool BackfillDone, bool DiskLow, bool UnknownFormat)
{
public static AlertEvents All { get; } = new(true, true, true, true, true, true);
}
/// <summary>
/// Where and when Febe sends alerts (Impostazioni, Notifiche; spec §13.3): the events, Windows notifications (desktop),
/// Telegram with the bot token and the chat identifier. The token is a secret: it is stored in the settings table of
/// the Data folder, never logged, never sent back to the interface.
/// </summary>
public sealed record AlertSettings(AlertEvents Events, bool WindowsNotifications, string? TelegramChatId, string? TelegramToken)
{
public static AlertSettings Default { get; } = new(AlertEvents.All, true, null, null);
/// <summary>Both the bot token and the chat identifier are set.</summary>
public bool TelegramConfigured => !string.IsNullOrWhiteSpace(TelegramToken) && !string.IsNullOrWhiteSpace(TelegramChatId);
/// <summary>Never prints the token.</summary>
public override string ToString() =>
$"AlertSettings {{ Events = {Events}, WindowsNotifications = {WindowsNotifications}, TelegramChatId = {(TelegramChatId is null ? "-" : "impostato")}, TelegramToken = {(TelegramToken is null ? "-" : "***")} }}";
}
/// <summary>Setting keys of the alerts (spec §8.3 <c>setting</c>).</summary>
public static class AlertSettingKeys
{
public const string Verification = "avvisi.verifica";
public const string Disconnection = "avvisi.disconnessione";
public const string Throttle = "avvisi.rallentamento";
public const string BackfillDone = "avvisi.storico-completato";
public const string DiskLow = "avvisi.disco-quasi-pieno";
public const string UnknownFormat = "avvisi.formato-non-riconosciuto";
public const string Windows = "avvisi.windows";
public const string TelegramChat = "avvisi.telegram.chat";
/// <summary>The bot token: a secret (rule 10), never logged nor shown.</summary>
public const string TelegramToken = "avvisi.telegram.gettone";
}
/// <summary>Reads and writes <see cref="AlertSettings"/>.</summary>
public static class AlertSettingsStore
{
public static async Task<AlertSettings> LoadAsync(ISettingsStore store, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(store);
var all = await store.GetAllAsync(ct).ConfigureAwait(false);
bool Flag(string key) => !all.TryGetValue(key, out var text) || !bool.TryParse(text, out var value) || value;
string? Text(string key) => all.TryGetValue(key, out var text) && !string.IsNullOrWhiteSpace(text) ? text : null;
return new AlertSettings(
new AlertEvents(
Flag(AlertSettingKeys.Verification),
Flag(AlertSettingKeys.Disconnection),
Flag(AlertSettingKeys.Throttle),
Flag(AlertSettingKeys.BackfillDone),
Flag(AlertSettingKeys.DiskLow),
Flag(AlertSettingKeys.UnknownFormat)),
Flag(AlertSettingKeys.Windows),
Text(AlertSettingKeys.TelegramChat),
Text(AlertSettingKeys.TelegramToken));
}
/// <summary>Stores the settings in one transaction (a null token or chat removes it).</summary>
public static Task SaveAsync(ISettingsStore store, AlertSettings settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(settings);
static string B(bool value) => value ? "true" : "false";
return store.SetManyAsync(
new Dictionary<string, string?>
{
[AlertSettingKeys.Verification] = B(settings.Events.Verification),
[AlertSettingKeys.Disconnection] = B(settings.Events.Disconnection),
[AlertSettingKeys.Throttle] = B(settings.Events.Throttle),
[AlertSettingKeys.BackfillDone] = B(settings.Events.BackfillDone),
[AlertSettingKeys.DiskLow] = B(settings.Events.DiskLow),
[AlertSettingKeys.UnknownFormat] = B(settings.Events.UnknownFormat),
[AlertSettingKeys.Windows] = B(settings.WindowsNotifications),
[AlertSettingKeys.TelegramChat] = string.IsNullOrWhiteSpace(settings.TelegramChatId) ? null : settings.TelegramChatId.Trim(),
[AlertSettingKeys.TelegramToken] = string.IsNullOrWhiteSpace(settings.TelegramToken) ? null : settings.TelegramToken.Trim(),
},
ct);
}
}
/// <summary>Outcome of «Invia una prova».</summary>
/// <param name="Sent">The message left.</param>
/// <param name="Message">Italian text for the page: what happened and what to do.</param>
public sealed record AlertTestResult(bool Sent, string Message);
/// <summary>
/// «Invia una prova» of the Telegram alerts (spec §13.3). The real sender (one HTTPS call with <c>HttpClient</c>, no
/// library, the address never logged because it contains the token) arrives with milestone M8 and replaces
/// <see cref="TelegramNotAvailableYet"/>.
/// </summary>
public interface IAlertTestSender
{
Task<AlertTestResult> SendTelegramTestAsync(AlertSettings settings, CancellationToken ct);
}
/// <summary>Until M8: no message leaves, and the page says so plainly.</summary>
public sealed class TelegramNotAvailableYet : IAlertTestSender
{
public const string Text =
"Le impostazioni sono salvate, ma l'invio dei messaggi Telegram non c'è ancora in questa versione di Febe (arriva con la tappa M8): nessun messaggio è partito, nemmeno di prova.";
public Task<AlertTestResult> SendTelegramTestAsync(AlertSettings settings, CancellationToken ct) => Task.FromResult(new AlertTestResult(false, Text));
}
+29
View File
@@ -64,6 +64,35 @@ public sealed partial class DailyBackup(IDatabaseMaintenance database, IClock cl
return new BackupResult(created, ApplyRetention(today));
}
/// <summary>
/// «Fai una copia adesso» (Impostazioni, Dati): a fresh copy of the database now. It becomes today's copy, replacing
/// the one made earlier today only after the new one is complete (one copy per day, as the retention expects).
/// Then the retention is applied.
/// </summary>
public async Task<BackupResult> RunNowAsync(CancellationToken ct = default)
{
Directory.CreateDirectory(Folder);
var today = LocalCalendar.Today(clock.Now, clock.LocalZone);
var target = Path.Combine(Folder, FileNameFor(today));
var part = target + "." + Guid.NewGuid().ToString("N")[..8] + PartSuffix;
BackupFile created;
try
{
await database.BackupToAsync(part, ct).ConfigureAwait(false);
File.Move(part, target, overwrite: true);
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()
{
@@ -0,0 +1,327 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Library;
/// <summary>One side of a probable duplicate found after a download (spec §9.5): a file of the library.</summary>
/// <param name="MediaId">The file.</param>
/// <param name="EntryId">Its entry.</param>
/// <param name="AccountId">The account.</param>
/// <param name="Username">The account's user name.</param>
/// <param name="EntryKind">Post, story, highlight…</param>
/// <param name="Kind">Photo or video.</param>
/// <param name="Width">Width in pixels.</param>
/// <param name="Height">Height in pixels.</param>
/// <param name="Bytes">Size on disk.</param>
/// <param name="PublishedAt">Publication of the entry.</param>
/// <param name="Provenance">Downloaded or imported.</param>
/// <param name="Sha256">SHA-256: the thumbnail key.</param>
/// <param name="HasThumbnail">A thumbnail exists.</param>
/// <param name="RelativePath">Path relative to the account folder.</param>
/// <param name="FilesInEntry">Files of the entry still present.</param>
/// <param name="Present">The file is still in the library (not deleted meanwhile).</param>
public sealed record DownloadDuplicateSide(
long MediaId,
long EntryId,
long AccountId,
string Username,
EntryKind EntryKind,
MediaKind Kind,
int? Width,
int? Height,
long? Bytes,
DateTimeOffset PublishedAt,
Provenance Provenance,
string? Sha256,
bool HasThumbnail,
string? RelativePath,
int FilesInEntry,
bool Present);
/// <summary>A probable duplicate after a download: the file already there and the one just downloaded.</summary>
/// <param name="Pair">The stored pair (Pending until Alberto chooses: nothing is decided in advance).</param>
/// <param name="Existing">The file that was already in the library.</param>
/// <param name="Candidate">The file just downloaded.</param>
/// <param name="CandidateIsLarger">The «Più grande» badge goes on the downloaded file (more pixels, then more bytes).</param>
public sealed record DownloadDuplicateCase(DuplicatePair Pair, DownloadDuplicateSide Existing, DownloadDuplicateSide Candidate, bool CandidateIsLarger);
/// <summary>What a decision did.</summary>
/// <param name="Decided">Pairs decided (more than one with «applica a tutti i casi simili»).</param>
/// <param name="FilesRemoved">Files removed from the library by the decision.</param>
/// <param name="Problems">Italian notes on files that could not be removed (they stay, nothing is lost).</param>
public sealed record DownloadDecisionResult(int Decided, int FilesRemoved, IReadOnlyList<string> Problems);
/// <summary>
/// The review of the probable duplicates found after a download (spec §9.5, §10.3): the same comparison as mockup 09
/// for <c>duplicate_pair</c> rows with origin «download». Both files stay in the library until Alberto decides; only his
/// explicit choice removes one (rule 12):
/// <list type="bullet">
/// <item>«Tienili entrambi»: nothing is removed.</item>
/// <item>«Tieni quello in libreria»: the file just downloaded goes.</item>
/// <item>«Tieni il più grande»: the smaller goes (more pixels, then more bytes; on a tie the one already there stays).</item>
/// </list>
/// A removed file whose entry has no other file is deleted as «Elimina dalla libreria» with the choice remembered, so it
/// is not downloaded again; a file of a series leaves only its position (marked «eliminato»), and the journal of the
/// account receives the entry again with the files that remain.
/// </summary>
public sealed class DownloadDuplicateReview(
IFebeStorage storage,
LibraryLayout layout,
AccountJournal journal,
IClock clock,
ThumbnailStore? thumbnails = null,
PerceptualHashIndex? hashIndex = null)
{
public Task<int> CountPendingAsync(CancellationToken ct = default) => storage.Duplicates.CountPendingAsync(DuplicateOrigin.Download, ct);
/// <summary>Pending cases in creation order, after <paramref name="afterPairId"/>. Pairs whose files are gone are skipped.</summary>
public async Task<IReadOnlyList<DownloadDuplicateCase>> ListAsync(long afterPairId = 0, int limit = 50, CancellationToken ct = default)
{
var list = new List<DownloadDuplicateCase>();
var after = afterPairId;
while (list.Count < limit)
{
var pairs = await storage.Duplicates.ListPendingAsync(DuplicateOrigin.Download, after, Math.Max(limit, 50), ct).ConfigureAwait(false);
if (pairs.Count == 0)
{
break;
}
foreach (var pair in pairs)
{
after = pair.Id;
if (await BuildAsync(pair, ct).ConfigureAwait(false) is { } found)
{
list.Add(found);
if (list.Count >= limit)
{
break;
}
}
}
}
return list;
}
public async Task<DownloadDuplicateCase?> GetAsync(long pairId, CancellationToken ct = default)
{
var pair = await storage.Duplicates.GetAsync(pairId, ct).ConfigureAwait(false);
return pair is { Origin: DuplicateOrigin.Download } ? await BuildAsync(pair, ct).ConfigureAwait(false) : null;
}
/// <summary>
/// Alberto's decision on a pair; with <paramref name="applyToAllPending"/> the same choice goes to every pending pair
/// of downloads («Applica a tutti i casi simili»). Throws <see cref="KeyNotFoundException"/> for an unknown pair and
/// <see cref="ArgumentException"/> for <see cref="DuplicateDecision.Pending"/>.
/// </summary>
public async Task<DownloadDecisionResult> DecideAsync(long pairId, DuplicateDecision decision, bool applyToAllPending = false, CancellationToken ct = default)
{
if (decision == DuplicateDecision.Pending)
{
throw new ArgumentException("Scegli che cosa tenere: il più grande, quello già in libreria oppure entrambi.", nameof(decision));
}
var first = await GetAsync(pairId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException("Questo doppione non c'è più: forse è già stato deciso.");
var cases = new List<DownloadDuplicateCase> { first };
if (applyToAllPending)
{
var after = 0L;
while (true)
{
var page = await ListAsync(after, 200, ct).ConfigureAwait(false);
if (page.Count == 0)
{
break;
}
cases.AddRange(page.Where(c => c.Pair.Id != pairId));
after = page[^1].Pair.Id;
}
}
var removed = 0;
var problems = new List<string>();
var gone = new HashSet<long>();
foreach (var item in cases)
{
ct.ThrowIfCancellationRequested();
if (gone.Contains(item.Existing.MediaId) || gone.Contains(item.Candidate.MediaId))
{
// One of its files went with an earlier decision of the same batch: this pair is decided without
// removing anything else (nothing is removed twice, nothing is lost).
await storage.Duplicates.DecideAsync(item.Pair.Id, DuplicateDecision.KeepBoth, clock.Now, ct).ConfigureAwait(false);
continue;
}
var loser = decision switch
{
DuplicateDecision.KeepExisting => item.Candidate,
DuplicateDecision.KeepLarger => item.CandidateIsLarger ? item.Existing : item.Candidate,
_ => null,
};
// From here the decision goes to the end: it is recorded first, then applied.
await storage.Duplicates.DecideAsync(item.Pair.Id, decision, clock.Now, CancellationToken.None).ConfigureAwait(false);
if (loser is not { Present: true })
{
continue;
}
var (ok, problem) = await RemoveAsync(loser, CancellationToken.None).ConfigureAwait(false);
gone.Add(loser.MediaId);
if (ok)
{
removed++;
}
else if (problem is not null)
{
problems.Add(problem);
}
}
return new DownloadDecisionResult(cases.Count, removed, problems);
}
/// <summary>True when the candidate is larger: more pixels, then more bytes; a tie keeps the file already there.</summary>
public static bool IsLarger(DownloadDuplicateSide candidate, DownloadDuplicateSide existing)
{
ArgumentNullException.ThrowIfNull(candidate);
ArgumentNullException.ThrowIfNull(existing);
var a = (long)(candidate.Width ?? 0) * (candidate.Height ?? 0);
var b = (long)(existing.Width ?? 0) * (existing.Height ?? 0);
if (a != b)
{
return a > b;
}
return (candidate.Bytes ?? 0) > (existing.Bytes ?? 0);
}
private async Task<DownloadDuplicateCase?> BuildAsync(DuplicatePair pair, CancellationToken ct)
{
if (pair.ExistingMediaId is not { } existingId || pair.CandidateMediaId is not { } candidateId)
{
return null;
}
var existing = await SideAsync(existingId, ct).ConfigureAwait(false);
var candidate = await SideAsync(candidateId, ct).ConfigureAwait(false);
if (existing is null || candidate is null)
{
return null;
}
return new DownloadDuplicateCase(pair, existing, candidate, IsLarger(candidate, existing));
}
private async Task<DownloadDuplicateSide?> SideAsync(long mediaId, CancellationToken ct)
{
var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false);
if (media is null)
{
return null;
}
var stored = await storage.Entries.GetWithMediaAsync(media.EntryId, ct).ConfigureAwait(false);
if (stored is null)
{
return null;
}
var account = await storage.Accounts.GetAsync(stored.Entry.AccountId, ct).ConfigureAwait(false);
if (account is null)
{
return null;
}
return new DownloadDuplicateSide(
media.Id,
stored.Entry.Id,
account.Id,
account.Username,
stored.Entry.Kind,
media.Kind,
media.Width,
media.Height,
media.Bytes,
stored.Entry.PublishedAt,
stored.Entry.Provenance,
media.Sha256,
media.HasThumbnail,
media.RelativePath,
stored.Media.Count(m => EntryStateRules.IsPresent(m.State)),
EntryStateRules.IsPresent(media.State));
}
private async Task<(bool Removed, string? Problem)> RemoveAsync(DownloadDuplicateSide side, CancellationToken ct)
{
if (side.FilesInEntry <= 1)
{
var deletion = new LibraryDeletion(storage, layout, journal, clock, thumbnails, hashIndex);
var result = await deletion.DeleteAsync(side.EntryId, DeletionMode.Remember, ct).ConfigureAwait(false);
return result.FailedFiles.Count == 0
? (true, null)
: (false, $"@{side.Username}: {string.Join("; ", result.FailedFiles)}. Il file resta sul disco; l'elemento è segnato come eliminato.");
}
// A file of a series: only this position goes; the entry and its other files stay.
var stored = await storage.Entries.GetWithMediaAsync(side.EntryId, ct).ConfigureAwait(false);
var account = await storage.Accounts.GetAsync(side.AccountId, ct).ConfigureAwait(false);
var media = stored?.Media.FirstOrDefault(m => m.Id == side.MediaId);
if (stored is null || account is null || media is null)
{
return (false, null);
}
var folder = layout.AccountFolder(account);
await storage.Media.UpdateAsync(media with { State = MediaState.Deleted }, ct).ConfigureAwait(false);
await storage.Entries.RecomputeStateAsync(stored.Entry.Id, ct).ConfigureAwait(false);
hashIndex?.Remove(media.Id);
var remaining = stored.Media.Select(m => m.Id == media.Id ? m with { State = MediaState.Deleted } : m).ToList();
var highlights = await storage.Highlights.ListForEntryAsync(stored.Entry.Id, ct).ConfigureAwait(false);
await journal.AppendSavedAsync(
folder,
account,
stored.Entry,
remaining,
highlights.Select(h => new JournalHighlight(h.InstagramId, h.Title, h.Position)).ToList(),
ct).ConfigureAwait(false);
string? problem = null;
if (media.RelativePath is { } relative)
{
try
{
var path = LibraryLayout.FullPath(folder, relative);
if (File.Exists(path))
{
File.Delete(path);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
{
problem = $"@{side.Username}, {relative}: {ex.Message}. Il file resta sul disco.";
}
}
if (thumbnails is not null && media.Sha256 is { } sha)
{
var users = await storage.Media.FindBySha256Async(sha, ct).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.
}
}
}
return (problem is null, problem);
}
}