E2: API delle copie esterne, composizione e dimostrazione

Le copie esterne diventano usabili dall'interfaccia: ExportHub costruisce
l'unico ExportService del web (segna «interrotto» ciò che l'arresto ha
fermato e avvisa le pagine a lavoro finito), ExportApi espone cartelle,
scelta e controllo della cartella, «Copia in…» (piano e avvio), «Copia di
nuovo», avanzamento, lavori, ripresa, annullamento e resoconto.

Gli endpoint esistenti portano le copie: filtro copies= della Libreria,
segno «Copiato» / «Copiato in parte 1/3» sulle tessere, copie di ogni file
nel visualizzatore, riquadro «Copie esterne» e interruttore «Esporta questo
account» nella scheda. Una cartella di account o della libreria che
finirebbe dentro (o attorno a) una cartella delle copie è rifiutata; dopo
una ricostruzione le cartelle in conflitto vanno in pausa.

Composizione: in Docker le copie si scrivono solo sotto /esporta, e solo
con --esporta/FEBE_ESPORTA e un montaggio (riga di avvio e avviso se manca);
sul desktop qualsiasi cartella con la finestra del sistema e lo spazio
libero misurato anche sulle condivisioni di rete. La dimostrazione ha una
cartella generale, una propria, un account non esportato e copie vere in
ogni stato, scritte dal motore nella sua cartella temporanea.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 11:42:02 +01:00
1 parent a112c92893
commit 4a7925ad23
30 files changed
+2299 -32

No files matched your search

+151 -5
View File
@@ -2,6 +2,7 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Web.Library;
@@ -41,8 +42,9 @@ public static class LibraryApi
var end = LocalCalendar.StartOfDay(d.Day.AddDays(1), zone);
return new DayDto(ApiMapping.Day(d.Day), d.Count, ApiMapping.Cursor(new LibraryCursor(end, 0), mode));
}).ToList();
var hasDestinations = await HasDestinationsAsync(storage, ct).ConfigureAwait(false);
return ApiHttp.Json(
new LibraryDaysDto(now.ToUnixTimeMilliseconds(), ApiMapping.Day(LocalCalendar.Today(now, zone)), totals.Entries, totals.Accounts, list, files),
new LibraryDaysDto(now.ToUnixTimeMilliseconds(), ApiMapping.Day(LocalCalendar.Today(now, zone)), totals.Entries, totals.Accounts, list, files, hasDestinations),
FebeJsonContext.Default.LibraryDaysDto);
});
@@ -65,7 +67,7 @@ public static class LibraryApi
ct).ConfigureAwait(false);
return ApiHttp.Json(
new LibraryPageDto(
page.Tiles.Select(t => Tile(t, zone)).ToList(),
await TilesAsync(storage, page.Tiles, zone, ct).ConfigureAwait(false),
page.Older is { } older ? ApiMapping.Cursor(older, mode) : null,
page.Newer is { } newer ? ApiMapping.Cursor(newer, mode) : null),
FebeJsonContext.Default.LibraryPageDto);
@@ -76,7 +78,7 @@ public static class LibraryApi
{
var ids = ParseIds(context.Request.Query["ids"].ToString());
var tiles = await storage.Entries.GetTilesAsync(ids, ct).ConfigureAwait(false);
return ApiHttp.Json(new LibraryPageDto(tiles.Select(t => Tile(t, clock.LocalZone)).ToList(), null, null), FebeJsonContext.Default.LibraryPageDto);
return ApiHttp.Json(new LibraryPageDto(await TilesAsync(storage, tiles, clock.LocalZone, ct).ConfigureAwait(false), null, null), FebeJsonContext.Default.LibraryPageDto);
});
endpoints.MapGet("/api/thumbnails/{key}", (string key, HttpContext context, FebeLibrary library) =>
@@ -233,6 +235,7 @@ public static class LibraryApi
var local = LocalCalendar.ToLocal(entry.PublishedAt, zone);
var accountFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(library.Layout.AccountFolder(account)));
var avatar = await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false);
var copies = await EntryCopiesContext.LoadAsync(storage, account, ct).ConfigureAwait(false);
var media = new List<MediaDto>(stored.Media.Count);
foreach (var m in stored.Media)
{
@@ -259,7 +262,8 @@ public static class LibraryApi
m.HasThumbnail && m.Sha256 is not null ? m.Sha256 : m.Kind == MediaKind.Video ? "video" : null,
path is not null,
ApiMapping.State(m.State),
damaged));
damaged,
copies is null ? null : await copies.CopiesAsync(storage, m, now, zone, ct).ConfigureAwait(false)));
}
return new EntryDto(
@@ -279,7 +283,149 @@ public static class LibraryApi
entry.DownloadedAt is { } d ? ApiMapping.Local(d, now, zone) : null,
highlights.Select(h => h.Title).ToList(),
entry.State == EntryState.Deleted ? null : InstagramLinks.For(account, entry, now, highlights.FirstOrDefault()?.InstagramId),
media);
media,
copies is { Effective: not null, Enabled: true });
}
/// <summary>
/// The tiles of a page with the mark of the copies to external folders (spec §4.6, tappa E2): an entry tile
/// «Copiato» or «Copiato in parte 1/3», a file tile of «Tutte le foto» «Copiato». Only due files count (decision
/// D3), and without a destination in use nothing more is asked to the database.
/// </summary>
public static async Task<IReadOnlyList<TileDto>> TilesAsync(IFebeStorage storage, IReadOnlyList<LibraryTile> tiles, TimeZoneInfo zone, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(tiles);
var list = tiles.Select(t => Tile(t, zone)).ToList();
if (list.Count == 0 || !await HasDestinationsAsync(storage, ct).ConfigureAwait(false))
{
return list;
}
var fileIds = tiles.Where(t => t.FilePosition is not null && t.CoverMediaId is not null).Select(t => t.CoverMediaId!.Value).Distinct().ToList();
var entryIds = tiles.Where(t => t.FilePosition is null).Select(t => t.EntryId).Distinct().ToList();
var fileMarks = fileIds.Count == 0 ? null : await storage.Exports.GetFileMarksAsync(fileIds, ct).ConfigureAwait(false);
var entryCopies = entryIds.Count == 0 ? null : await storage.Exports.GetEntryCopyCountsAsync(entryIds, ct).ConfigureAwait(false);
for (var i = 0; i < list.Count; i++)
{
var tile = tiles[i];
if (tile.FilePosition is not null)
{
if (tile.CoverMediaId is { } mediaId && fileMarks is not null && fileMarks.TryGetValue(mediaId, out var mark) && mark == ExportMark.Copied)
{
list[i] = list[i] with { Copies = "copied" };
}
}
else if (entryCopies is not null && entryCopies.TryGetValue(tile.EntryId, out var copies))
{
list[i] = copies.Mark switch
{
ExportMark.Copied => list[i] with { Copies = "copied" },
ExportMark.Partly => list[i] with { Copies = "partly", CopiesDone = copies.Copied, CopiesDue = copies.Due },
_ => list[i],
};
}
}
return list;
}
/// <summary>Whether any destination of the copies is in use (the marks and the «Copie» filter make sense).</summary>
public static async Task<bool> HasDestinationsAsync(IFebeStorage storage, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
return (await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false)).Count > 0;
}
/// <summary>
/// What the viewer needs to list the copies of the files of one entry (spec §4.6, §4.10): every destination, retired
/// ones too (an old copy keeps its name), the effective destination of the account and its switch, and «Lo stesso
/// post in due account». Null when no destination was ever added.
/// </summary>
private sealed record EntryCopiesContext(
Account Account,
IReadOnlyDictionary<long, ExportDestination> Destinations,
ExportDestination? Effective,
bool Enabled,
SamePostCopies SamePost,
IReadOnlyDictionary<long, string> Usernames)
{
/// <summary>Copies shown for one file, newest first.</summary>
public const int MaxShown = 6;
public static async Task<EntryCopiesContext?> LoadAsync(IFebeStorage storage, Account account, CancellationToken ct)
{
var exports = storage.Exports;
var destinations = await exports.ListDestinationsAsync(includeRetired: true, ct).ConfigureAwait(false);
if (destinations.Count == 0)
{
return null;
}
var effective = await exports.GetAccountDestinationAsync(account.Id, ct).ConfigureAwait(false)
?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false);
var enabled = ExportAccounts.IsEnabled(await exports.GetAccountExportEnabledAsync(account.Id, ct).ConfigureAwait(false));
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
var usernames = (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username);
return new EntryCopiesContext(account, destinations.ToDictionary(d => d.Id), effective, enabled, settings.SamePost, usernames);
}
public async Task<IReadOnlyList<MediaCopyDto>> CopiesAsync(IFebeStorage storage, Media media, DateTimeOffset now, TimeZoneInfo zone, CancellationToken ct)
{
if (media.Sha256 is not { Length: > 0 } sha)
{
return [];
}
var present = EntryStateRules.IsPresent(media.State);
var rows = await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false);
var shown = new List<MediaCopyDto>();
foreach (var copy in rows.OrderByDescending(c => c.StateChangedAt ?? c.CopiedAt).ThenByDescending(c => c.Id))
{
if (!Destinations.TryGetValue(copy.DestinationId, out var destination))
{
continue;
}
// The copies made for this account; with «Una copia sola», also the ones made for another account in a
// folder still in use (that is why this file is «Già copiato»).
var own = copy.AccountId == Account.Id;
if (!own && !(SamePost == SamePostCopies.OneOnly && copy.State == ExportCopyState.Copied && !destination.IsRetired))
{
continue;
}
var canCopyAgain = own
&& copy.State is ExportCopyState.Removed or ExportCopyState.Superseded
&& present
&& !destination.IsRetired
&& Enabled
&& Effective?.Id == destination.Id
&& !rows.Any(c => c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == Account.Id && c.DestinationId == destination.Id && c.Variant == copy.Variant);
shown.Add(new MediaCopyDto(
copy.Id,
ExportDestinations.Label(destination),
destination.IsRetired,
ExportApi.CopyState(copy.State),
copy.Variant switch
{
ExportVariant.Whole => "whole",
ExportVariant.Converted => "converted",
_ => "frame",
},
copy.Format == ExportFormat.Original ? null : copy.Format.ToString().ToLowerInvariant(),
copy.FrameAt is { } frame ? (long)frame.TotalMilliseconds : null,
ApiMapping.Local(copy.StateChangedAt ?? copy.CopiedAt, now, zone),
own ? null : copy.AccountId is { } other && Usernames.TryGetValue(other, out var name) ? name : null,
canCopyAgain));
if (shown.Count == MaxShown)
{
break;
}
}
return shown;
}
}
/// <summary>