E2: motore delle copie esterne (porta, destinazioni, piano, copia)

Prima metà della tappa E2 «Copie esterne» (#58), parte Core e Data:

- porta del lavoro lungo: importazione, copia e ricostruzione mai insieme;
- radice /esporta in Docker con mountinfo, controllo delle cartelle con
  il file di prova, destinazioni con «Esporta questo account» acceso se
  Alberto non ha mai scelto (decisione del 27/11/2026);
- filtro «Copie», segni delle tessere e conteggi dell'account sui soli
  file dovuti (D3);
- percorsi «Come la libreria», segmento dell'account nella cartella
  generale, 240 caratteri, storia in evidenza;
- piano di «Copia in…», un lavoro per destinazione, copia in .part con
  SHA-256 riletto dal disco, nome libero, mai sovrascrivere, adozione
  per percorso, pausa della destinazione su prova, spazio e FAT32,
  attesa fuori dalle sessioni del motore, ripresa e recupero;
- .part rimossi solo nelle cartelle degli elementi di lavori non finiti;
- «Tolto» e «Superato» (agganci in importazione, scaricamenti,
  doppioni e ricostruzione), mai ricopiati da soli;
- rapporti e testi in italiano, prove del lavoro di copia.

Interfaccia, API e composizione restano alla parte successiva.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 10:55:29 +01:00
1 parent 213b89a618
commit a112c92893
41 files changed
+5370 -27

No files matched your search

+42 -15
View File
@@ -343,13 +343,13 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
// in SQL, no sort, and the day bounds are computed once per day rather than once per entry.
var command = c.Command(string.Empty);
var files = mode == MosaicMode.Files;
var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter, aggregate: true);
var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter, aggregate: true, files: files);
var counts = files ? FileCounts(c, filter) : null;
var perEntry = files && counts is null;
command.CommandText = !files
? $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at"
: perEntry
? $"SELECT e.published_at, {FilesOfEntry(filter)} FROM entry e WHERE {where} ORDER BY e.published_at"
? $"SELECT e.published_at, {FilesOfEntry(c, filter)} FROM entry e WHERE {where} ORDER BY e.published_at"
: $"SELECT e.published_at, e.id FROM entry e WHERE {where} ORDER BY e.published_at";
var days = new List<DayCount>();
long dayStart = long.MaxValue, dayEnd = long.MinValue;
@@ -417,15 +417,22 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
// --------------------------------------------------------------------------------------------- «Tutte le foto»
/// <summary>The files of «Tutte le foto» on <c>media m</c>: those in the library, of the kind of «Foto» or «Video».</summary>
private static string FileTerms(LibraryFilter filter) =>
/// <summary>
/// The files of «Tutte le foto» on <c>media m</c>: those in the library, of the kind of «Foto» or «Video», and of the
/// class of the «Copie» filter. With «Copie» the term reads the entry <c>e</c> of the file too (account and kind), so
/// the caller must have it in scope (<see cref="NeedsEntry"/>).
/// </summary>
internal static string FileTerms(SqliteConnection c, LibraryFilter filter) =>
// The unary + keeps SQLite on the key of the entry (entry_id, position) rather than on the broad state index.
"+m.state IN ('Downloaded', 'Imported')" + filter.Kind switch
{
LibraryKindFilter.Photos => " AND m.kind = 'Photo'",
LibraryKindFilter.Videos => " AND m.kind = 'Video'",
_ => string.Empty,
};
} + (filter.Copies is { } copies ? " AND " + ExportFilterSql.FileTerm(ExportFilterSql.Load(c), copies) : string.Empty);
/// <summary>The file terms of this filter read the entry of the file (the «Copie» filter).</summary>
private static bool NeedsEntry(LibraryFilter filter) => filter.Copies is not null;
/// <summary>
/// The files of «Tutte le foto» of every entry, in one pass over ix_media_entry_files: over the whole library a
@@ -439,7 +446,8 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
return null;
}
using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM media m WHERE {FileTerms(filter)} GROUP BY m.entry_id");
var from = NeedsEntry(filter) ? "media m JOIN entry e ON e.id = m.entry_id" : "media m";
using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM {from} WHERE {FileTerms(c, filter)} GROUP BY m.entry_id");
var counts = new Dictionary<long, int>();
using var r = command.ExecuteReader();
while (r.Read())
@@ -459,8 +467,8 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
filter.Kind is LibraryKindFilter.Photos or LibraryKindFilter.Videos ? filter with { Kind = LibraryKindFilter.Posts } : filter;
/// <summary>A correlated count of the files of «Tutte le foto» of the entry <c>e</c>.</summary>
private static string FilesOfEntry(LibraryFilter filter) =>
$"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(filter)})";
private static string FilesOfEntry(SqliteConnection c, LibraryFilter filter) =>
$"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(c, filter)})";
/// <summary>
/// A window of «Tutte le foto»: the keys of the entries come from the same keyset scan of the publication index as
@@ -575,7 +583,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
private static List<(long Id, long PublishedAt)> EntryKeys(SqliteConnection c, LibraryFilter filter, LibraryCursor? cursor, bool newer, bool inclusive, int limit)
{
using var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
var where = BuildWhere(c, command, filter, files: true);
var sql = new StringBuilder($"SELECT e.id, e.published_at FROM entry e WHERE {where}");
if (cursor is { } at)
{
@@ -607,8 +615,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
{
using var command = c.Command(string.Empty);
var list = command.AddList("f", chunk);
var from = NeedsEntry(filter) ? "media m JOIN entry e ON e.id = m.entry_id" : "media m";
command.CommandText = "SELECT m.entry_id, m.id, m.position, m.kind, m.width, m.height, m.duration_ms, m.sha256, m.has_thumbnail "
+ $"FROM media m WHERE m.entry_id IN ({list}) AND {FileTerms(filter)} ORDER BY m.entry_id, m.position";
+ $"FROM {from} WHERE m.entry_id IN ({list}) AND {FileTerms(c, filter)} ORDER BY m.entry_id, m.position";
using var r = command.ExecuteReader();
while (r.Read())
{
@@ -638,11 +647,16 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
private static bool FileExists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older)
{
using var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
var terms = FileTerms(filter);
var where = BuildWhere(c, command, filter, files: true);
var terms = FileTerms(c, filter);
var position = older ? ">" : "<";
// With «Copie» the file terms read the entry: the first branch then joins it instead of testing it apart.
var first = NeedsEntry(filter)
? $"SELECT EXISTS (SELECT 1 FROM media m JOIN entry e ON e.id = m.entry_id WHERE m.entry_id = @xi AND m.position {position} @xn AND {terms} AND {where}) "
: $"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {position} @xn AND {terms} "
+ $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) ";
command.CommandText =
$"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {(older ? ">" : "<")} @xn AND {terms} "
+ $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) "
first
+ $"OR EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi) "
+ $"AND EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {terms}))";
command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId).With("@xn", (long)cursor.Position);
@@ -730,6 +744,13 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
}
/// <summary>The WHERE clause of a library filter on <c>entry e</c>; parameters are added to <paramref name="command"/>.</summary>
/// <param name="c">The connection (for the accounts of a search and the export tables of «Copie»).</param>
/// <param name="command">The command that gets the parameters.</param>
/// <param name="filter">The filter.</param>
/// <param name="files">
/// «Tutte le foto»: «Copie» keeps an entry when one of its files is of the chosen class, rather than judging the entry
/// as a whole (all its due files copied, for «Copiati»).
/// </param>
/// <param name="aggregate">
/// The clause is for a count over every entry of the filter (totals, day counts) rather than for a window. «Foto» and
/// «Video» then test the key of each post, on a covering index, against one list of the entries that have such
@@ -738,7 +759,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
/// hundred posts in index order.
/// With a filter on accounts the posts are few and the EXISTS is the cheaper of the two.
/// </param>
internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter, bool aggregate = false)
internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter, bool aggregate = false, bool files = false)
{
var byList = aggregate && filter.AccountIds is not { Count: > 0 };
// The unary + on kind and key keeps SQLite on a covering index of entry (kind, state and account in the index):
@@ -790,6 +811,12 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
command.With("@prov", Sql.Enum(provenance));
}
if (filter.Copies is { } copies)
{
var export = ExportFilterSql.Load(c);
parts.Add(files ? ExportFilterSql.EntryOfFiles(export, copies) : ExportFilterSql.EntryTerm(export, copies));
}
var term = TextSearch.Normalize(filter.Search);
if (term.Length > 0)
{
+225
View File
@@ -0,0 +1,225 @@
using System.Globalization;
using System.Text;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
/// <summary>
/// What the «Copie» filter, the tile marks and the account counts need of the export tables, read once per query:
/// the destinations in use, the switches that are off, «Una copia sola», and whether any copy, failure or removed or
/// superseded row exists at all (so the common cases pay nothing for what is not there).
/// </summary>
internal sealed record ExportFilterContext(
long? GeneralId,
ContentTypes GeneralTypes,
IReadOnlyList<(long AccountId, long DestinationId, ContentTypes Types)> Own,
IReadOnlySet<long> Off,
SamePostCopies SamePost,
bool HasCopies,
bool HasFailed,
bool HasHistory)
{
public bool HasDestination => GeneralId is not null || Own.Count > 0;
public IEnumerable<long> InUse => (GeneralId is { } g ? [g] : Array.Empty<long>()).Concat(Own.Select(o => o.DestinationId));
}
/// <summary>
/// The SQL of decision D3 of tappa E2 on <c>media m</c> joined to its <c>entry e</c>: a file is <b>due</b> when it is
/// present, its account has «Esporta questo account» on and an effective destination (its own folder in use, else the
/// general folder in use), and that destination takes its content type (D4). The values (ids and content types) are
/// integers from the database and are written into the text, so the terms can be repeated in one statement without
/// parameters colliding.
/// </summary>
internal static class ExportFilterSql
{
private const string Present = "m.sha256 IS NOT NULL AND +m.state IN ('Downloaded', 'Imported')";
/// <summary>The content type of a file as a bit of <see cref="ContentTypes"/>, as <see cref="ExportPaths.TypeOf"/>.</summary>
internal const string TypeOfFile =
"(CASE e.kind WHEN 'Post' THEN (CASE m.kind WHEN 'Photo' THEN 1 ELSE 2 END) "
+ "WHEN 'Story' THEN (4 | (CASE WHEN EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id) THEN 8 ELSE 0 END)) "
+ "WHEN 'Highlight' THEN 8 WHEN 'Tagged' THEN 16 WHEN 'ProfilePicture' THEN 32 ELSE 0 END)";
/// <summary>Reads the context of one query.</summary>
public static ExportFilterContext Load(SqliteConnection c)
{
long? general = null;
var generalTypes = ContentTypes.None;
var own = new List<(long, long, ContentTypes)>();
using (var r = c.Command("SELECT id, scope, account_id, content_types FROM export_destination WHERE removed_at IS NULL").ExecuteReader())
{
while (r.Read())
{
if (r.GetString(1) == nameof(ExportScope.General))
{
general = r.GetInt64(0);
generalTypes = (ContentTypes)r.GetInt32(3);
}
else if (r.GetInt64OrNull(2) is { } account)
{
own.Add((account, r.GetInt64(0), (ContentTypes)r.GetInt32(3)));
}
}
}
var off = new HashSet<long>();
using (var r = c.Command("SELECT account_id FROM export_account WHERE enabled = 0").ExecuteReader())
{
while (r.Read())
{
off.Add(r.GetInt64(0));
}
}
var samePost = c.Command("SELECT value FROM setting WHERE key = @k").With("@k", ExportSettingKeys.SamePost).ExecuteScalar() is string value
&& string.Equals(value, nameof(SamePostCopies.OneOnly), StringComparison.Ordinal)
? SamePostCopies.OneOnly
: SamePostCopies.OnePerAccount;
if (general is null && own.Count == 0)
{
return new ExportFilterContext(null, ContentTypes.None, own, off, samePost, false, false, false);
}
var inUse = string.Join(", ", (general is { } g ? [g] : Array.Empty<long>()).Concat(own.Select(o => o.Item2)).Select(Literal));
bool Any(string states) => c.Command(
$"SELECT EXISTS (SELECT 1 FROM export_copy WHERE destination_id IN ({inUse}) AND state IN ({states}))").ScalarInt64() != 0;
return new ExportFilterContext(general, generalTypes, own, off, samePost, Any("'Copied'"), Any("'Failed'"), Any("'Removed', 'Superseded'"));
}
/// <summary>The file <c>m</c> of entry <c>e</c> is due (D3).</summary>
public static string DueFile(ExportFilterContext x)
{
if (!x.HasDestination)
{
return "0";
}
var general = x.GeneralId is null ? "0" : TypeTerm(x.GeneralTypes);
var branches = new StringBuilder();
foreach (var (account, _, types) in x.Own)
{
branches.Append(CultureInfo.InvariantCulture, $" WHEN {account} THEN {(x.Off.Contains(account) ? "0" : TypeTerm(types))}");
}
foreach (var account in x.Off.Where(a => x.Own.All(o => o.AccountId != a)))
{
branches.Append(CultureInfo.InvariantCulture, $" WHEN {account} THEN 0");
}
var destination = branches.Length == 0 ? general : $"(CASE e.account_id{branches} ELSE {general} END)";
return destination == "1" ? $"({Present})" : $"({Present} AND {destination})";
}
/// <summary>The file is copied in its effective destination (or, with «Una copia sola», in any destination in use).</summary>
public static string Copied(ExportFilterContext x)
{
if (!x.HasCopies)
{
return "0";
}
return x.SamePost == SamePostCopies.OneOnly
? $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id IN ({InUse(x)}) AND c.state = 'Copied' AND c.variant <> 'Frame')"
: $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Copied' AND c.variant <> 'Frame')";
}
/// <summary>The last copy of the file in its effective destination failed («Non riuscito»): «Copia in…» tries again.</summary>
public static string Failed(ExportFilterContext x) => !x.HasFailed
? "0"
: $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Failed')";
/// <summary>
/// «Tolto o superato»: not copied, not failed, and its copy in the effective destination was removed, or a copy was
/// superseded (or removed) by this file. Never copied again by itself (D9). Two EXISTS, one per index.
/// </summary>
public static string Replaced(ExportFilterContext x)
{
if (!x.HasHistory)
{
return "0";
}
var destination = DestinationOf(x);
return $"(NOT {Copied(x)} AND NOT {Failed(x)} AND ("
+ $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
+ "AND c.state = 'Removed' AND c.superseded_by_sha256 IS NULL) "
+ $"OR EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
+ "AND c.state IN ('Superseded', 'Removed'))))";
}
/// <summary>«Non ancora copiato»: what «Copia in…» would copy (neither copied nor removed or superseded).</summary>
public static string NotCopied(ExportFilterContext x) => x.HasHistory ? $"(NOT {Copied(x)} AND NOT {Replaced(x)})" : $"(NOT {Copied(x)})";
/// <summary>The term of «Tutte le foto» on <c>m</c> (with <c>e</c> its entry): a due file of the chosen class.</summary>
public static string FileTerm(ExportFilterContext x, LibraryCopiesFilter filter) => filter switch
{
LibraryCopiesFilter.Copied => $"({DueFile(x)} AND {Copied(x)})",
LibraryCopiesFilter.NotCopied => $"({DueFile(x)} AND {NotCopied(x)})",
LibraryCopiesFilter.RemovedOrSuperseded => $"({DueFile(x)} AND {Replaced(x)})",
_ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null),
};
/// <summary>
/// The term of the grouped mosaic on <c>entry e</c>. «Copiati»: every due file copied, behind a list of the entries
/// with a copy (materialized once, a superset); «Non ancora copiati»: a due file to copy; «Tolti o superati»: a due
/// file removed or superseded, behind the list of the entries with such a row.
/// </summary>
public static string EntryTerm(ExportFilterContext x, LibraryCopiesFilter filter)
{
if (!x.HasDestination)
{
return "0";
}
string Files(string term) => $"EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {DueFile(x)} AND {term})";
return filter switch
{
LibraryCopiesFilter.Copied => !x.HasCopies
? "0"
: $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = c.source_sha256 WHERE c.destination_id IN ({InUse(x)}) "
+ $"AND c.state = 'Copied' AND c.variant <> 'Frame') AND {Files("1")} AND NOT {Files($"NOT {Copied(x)}")}",
LibraryCopiesFilter.NotCopied => Files(NotCopied(x)),
LibraryCopiesFilter.RemovedOrSuperseded => !x.HasHistory
? "0"
: $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = coalesce(c.superseded_by_sha256, c.source_sha256) "
+ $"WHERE c.destination_id IN ({InUse(x)}) AND c.state IN ('Removed', 'Superseded')) AND {Files(Replaced(x))}",
_ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null),
};
}
/// <summary>With «Tutte le foto» an entry qualifies when one of its files does.</summary>
public static string EntryOfFiles(ExportFilterContext x, LibraryCopiesFilter filter) =>
x.HasDestination ? $"EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {FileTerm(x, filter)})" : "0";
/// <summary>The effective destination of the account of <c>e</c>: its own folder, else the general one (NULL: none).</summary>
public static string DestinationOf(ExportFilterContext x)
{
var general = x.GeneralId is { } g ? Literal(g) : "NULL";
if (x.Own.Count == 0)
{
return general;
}
var builder = new StringBuilder("(CASE e.account_id");
foreach (var (account, destination, _) in x.Own)
{
builder.Append(CultureInfo.InvariantCulture, $" WHEN {account} THEN {destination}");
}
return builder.Append(CultureInfo.InvariantCulture, $" ELSE {general} END)").ToString();
}
private static string InUse(ExportFilterContext x) => string.Join(", ", x.InUse.Select(Literal));
private static string TypeTerm(ContentTypes types) =>
(types & ContentTypes.All) == ContentTypes.All ? "1"
: (types & ContentTypes.All) == ContentTypes.None ? "0"
: string.Create(CultureInfo.InvariantCulture, $"(({TypeOfFile} & {(int)(types & ContentTypes.All)}) <> 0)");
private static string Literal(long value) => value.ToString(CultureInfo.InvariantCulture);
}
+327
View File
@@ -1,4 +1,5 @@
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
@@ -868,4 +869,330 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
w.Command("DELETE FROM export_run WHERE id = @r").With("@r", runId).ExecuteNonQuery();
},
ct);
// Tappa E2 -------------------------------------------------------------------------------------------------------
/// <summary>SQLite allows 999 parameters per statement: id lists go in chunks below that.</summary>
private const int IdChunk = 900;
internal const string ReplacedCopySql = $"""
SELECT {CopyColumns} FROM export_copy
WHERE superseded_by_sha256 = @h AND destination_id = @d AND account_id = @a AND state IN ('Superseded', 'Removed')
ORDER BY id DESC LIMIT 1
""";
internal const string CopiedElsewhereSql = $"""
SELECT {CopyColumns} FROM export_copy
WHERE source_sha256 = @h AND variant = @v AND format = @f AND state = 'Copied' AND account_id IS NOT NULL
AND destination_id IN (SELECT id FROM export_destination WHERE removed_at IS NULL)
ORDER BY id DESC LIMIT 1
""";
internal const string RecentRunsSql = $"SELECT {RunColumns} FROM export_run ORDER BY started_at DESC, id DESC LIMIT @limit";
/// <summary>The whole copies of a destination for some originals (ix_export_copy_sha256); @d and the list of SHA-256.</summary>
internal static string CopyStatesSql(string shaList) => $"""
SELECT account_id, source_sha256, state, id FROM export_copy
WHERE source_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND variant = 'Whole' AND format = 'Original'
""";
/// <summary>The rows of a destination superseded or removed in favour of some files (ix_export_copy_superseded_by).</summary>
internal static string ReplacedStatesSql(string shaList) => $"""
SELECT account_id, superseded_by_sha256, state, id FROM export_copy
WHERE superseded_by_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND state IN ('Superseded', 'Removed')
""";
private const string CandidateColumns =
"m.id, m.entry_id, e.account_id, e.kind, m.kind, m.state, m.sha256, m.bytes, m.relative_path, m.position, "
+ "EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id)";
private static ExportCandidate ReadCandidate(SqliteDataReader r) => new(
r.GetInt64(0),
r.GetInt64(1),
r.GetInt64(2),
r.GetEnum<EntryKind>(3),
r.GetEnum<MediaKind>(4),
r.GetEnum<MediaState>(5),
r.GetTextOrNull(6),
r.GetInt64OrNull(7),
r.GetTextOrNull(8),
r.GetInt32(9),
r.GetBool(10));
public Task<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyDictionary<long, bool>>(
c =>
{
var switches = new Dictionary<long, bool>();
using var r = c.Command("SELECT account_id, enabled FROM export_account").ExecuteReader();
while (r.Read())
{
switches[r.GetInt64(0)] = r.GetBool(1);
}
return switches;
},
ct);
public Task<ExportCopy?> FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default)
{
var sha = ExportValues.Sha(sha256, nameof(sha256));
return db.ReadAsync(
c => ReadFirst(c.Command(ReplacedCopySql).With("@h", sha).With("@d", destinationId).With("@a", accountId), ReadCopy),
ct);
}
public Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, CancellationToken ct = default)
{
var sha = ExportValues.Sha(sha256, nameof(sha256));
return db.ReadAsync(
c => ReadFirst(c.Command(CopiedElsewhereSql).With("@h", sha).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)), ReadCopy),
ct);
}
public Task<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>> GetCopyStatesAsync(
long destinationId,
IReadOnlyCollection<(long AccountId, string Sha256)> keys,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(keys);
var wanted = keys.Select(k => (k.AccountId, Sha256: ExportValues.Sha(k.Sha256, nameof(keys)))).ToHashSet();
return db.ReadAsync<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>(
c =>
{
// Per pair: the current row (Copied or Failed), else the newest row when Removed or Superseded, else a row
// replaced by this file. Rows of other accounts that share a SHA-256 are read and dropped here.
var current = new Dictionary<(long, string), ExportCopyState>();
var newest = new Dictionary<(long, string), (long Id, ExportCopyState State)>();
var replaced = new Dictionary<(long, string), (long Id, ExportCopyState State)>();
void Keep(Dictionary<(long, string), (long Id, ExportCopyState State)> into, (long, string) key, long id, ExportCopyState state)
{
if (!into.TryGetValue(key, out var seen) || seen.Id < id)
{
into[key] = (id, state);
}
}
void Read(Func<string, string> sql, string[] chunk, Action<(long, string), ExportCopyState, long> add)
{
using var command = c.Command(string.Empty).With("@d", destinationId);
command.CommandText = sql(command.AddList("h", chunk));
using var r = command.ExecuteReader();
while (r.Read())
{
var key = (r.GetInt64(0), r.GetString(1));
if (wanted.Contains(key))
{
add(key, r.GetEnum<ExportCopyState>(2), r.GetInt64(3));
}
}
}
foreach (var chunk in wanted.Select(k => k.Sha256).Distinct(StringComparer.Ordinal).Chunk(IdChunk))
{
Read(CopyStatesSql, chunk, (key, state, id) =>
{
if (state is ExportCopyState.Copied or ExportCopyState.Failed)
{
current[key] = state;
}
else
{
Keep(newest, key, id, state);
}
});
Read(ReplacedStatesSql, chunk, (key, state, id) => Keep(replaced, key, id, state));
}
var result = new Dictionary<(long AccountId, string Sha256), ExportCopyState>();
foreach (var key in wanted)
{
if (current.TryGetValue(key, out var state))
{
result[key] = state;
}
else if (newest.TryGetValue(key, out var history))
{
result[key] = history.State;
}
else if (replaced.TryGetValue(key, out var by))
{
result[key] = by.State;
}
}
return result;
},
ct);
}
public Task<int> MarkCopiesRemovedAsync(IReadOnlyList<long> copyIds, DateTimeOffset at, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(copyIds);
if (copyIds.Count == 0)
{
return Task.FromResult(0);
}
return db.WriteAsync(
w =>
{
var changed = 0;
foreach (var chunk in copyIds.Distinct().Chunk(IdChunk))
{
var command = w.Command(string.Empty).With("@at", Sql.Time(at));
var list = command.AddList("i", chunk);
// A Superseded row keeps the SHA-256 of the file that replaced it: still never copied again by itself.
command.CommandText = $"UPDATE export_copy SET state = 'Removed', state_changed_at = @at WHERE id IN ({list}) AND state IN ('Copied', 'Superseded')";
changed += command.ExecuteNonQuery();
}
return changed;
},
ct);
}
public Task<IReadOnlyList<ExportCandidate>> ListCandidatesAsync(ExportSelection selection, long afterMediaId, int limit, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(selection);
var n = Math.Clamp(limit, 1, 10_000);
return db.ReadAsync<IReadOnlyList<ExportCandidate>>(
c =>
{
List<ExportCandidate> Page(Func<SqliteCommand, string> where)
{
using var command = c.Command(string.Empty).With("@after", afterMediaId).With("@n", (long)n);
var terms = where(command);
command.CommandText = $"SELECT {CandidateColumns} FROM media m JOIN entry e ON e.id = m.entry_id WHERE {terms} AND m.id > @after ORDER BY m.id LIMIT @n";
return ReadAll(command, ReadCandidate);
}
// Id lists go in chunks: each chunk gives its first n files after the key, and the first n of all of them are
// the page.
List<ExportCandidate> ByIds(IReadOnlyList<long> ids, string column) =>
ids.Distinct().Chunk(IdChunk)
.SelectMany(chunk => Page(command => $"{column} IN ({command.AddList("x", chunk)})"))
.OrderBy(x => x.MediaId)
.Take(n)
.ToList();
return selection switch
{
ExportSelection.Media media => ByIds(media.MediaIds, "m.id"),
ExportSelection.Entries entries => ByIds(entries.EntryIds, "m.entry_id"),
ExportSelection.Account account => Page(command =>
{
command.With("@acc", account.AccountId);
return $"e.account_id = @acc AND +e.state IN ({command.AddList("st", EntryStateRules.Visible.Select(s => s.ToString()))})";
}),
ExportSelection.Filter filter => Page(command =>
{
var where = EntryStore.BuildWhere(c, command, filter.LibraryFilter, aggregate: true, files: filter.Mode == MosaicMode.Files);
// «Tutte le foto»: only the files the mosaic shows (EntryStore.FileTerms, on m with its entry e).
return filter.Mode == MosaicMode.Files ? $"{where} AND {EntryStore.FileTerms(c, filter.LibraryFilter)}" : where;
}),
_ => throw new ArgumentOutOfRangeException(nameof(selection)),
};
},
ct);
}
public Task<IReadOnlyList<ExportRun>> ListRecentRunsAsync(int limit, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ExportRun>>(
c => ReadAll(c.Command(RecentRunsSql).With("@limit", (long)Math.Clamp(limit, 1, 1000)), ReadRun),
ct);
public Task<IReadOnlyDictionary<long, ExportMark>> GetEntryMarksAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entryIds);
return db.ReadAsync<IReadOnlyDictionary<long, ExportMark>>(
c =>
{
var marks = new Dictionary<long, ExportMark>();
var x = ExportFilterSql.Load(c);
if (!x.HasDestination || entryIds.Count == 0)
{
return marks;
}
foreach (var chunk in entryIds.Distinct().Chunk(IdChunk))
{
using var command = c.Command(string.Empty);
var list = command.AddList("x", chunk);
command.CommandText = $"""
SELECT m.entry_id, COUNT(*), SUM(CASE WHEN {ExportFilterSql.Copied(x)} THEN 1 ELSE 0 END)
FROM media m JOIN entry e ON e.id = m.entry_id
WHERE m.entry_id IN ({list}) AND {ExportFilterSql.DueFile(x)}
GROUP BY m.entry_id
""";
using var r = command.ExecuteReader();
while (r.Read())
{
var due = r.GetInt32(1);
var copied = r.GetInt32(2);
marks[r.GetInt64(0)] = copied == 0 ? ExportMark.None : copied >= due ? ExportMark.Copied : ExportMark.Partly;
}
}
return marks;
},
ct);
}
public Task<IReadOnlyDictionary<long, ExportMark>> GetFileMarksAsync(IReadOnlyList<long> mediaIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(mediaIds);
return db.ReadAsync<IReadOnlyDictionary<long, ExportMark>>(
c =>
{
var marks = new Dictionary<long, ExportMark>();
var x = ExportFilterSql.Load(c);
if (!x.HasDestination || mediaIds.Count == 0)
{
return marks;
}
foreach (var chunk in mediaIds.Distinct().Chunk(IdChunk))
{
using var command = c.Command(string.Empty);
var list = command.AddList("x", chunk);
command.CommandText = $"""
SELECT m.id, {ExportFilterSql.Copied(x)} FROM media m JOIN entry e ON e.id = m.entry_id
WHERE m.id IN ({list}) AND {ExportFilterSql.DueFile(x)}
""";
using var r = command.ExecuteReader();
while (r.Read())
{
marks[r.GetInt64(0)] = r.GetInt64(1) != 0 ? ExportMark.Copied : ExportMark.None;
}
}
return marks;
},
ct);
}
public Task<ExportAccountCounts> CountAccountFilesAsync(long accountId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var x = ExportFilterSql.Load(c);
if (!x.HasDestination)
{
return new ExportAccountCounts(0, 0, 0, 0);
}
using var command = c.Command($"""
SELECT COUNT(*),
ifnull(SUM(CASE WHEN {ExportFilterSql.NotCopied(x)} THEN 1 ELSE 0 END), 0),
ifnull(SUM(CASE WHEN {ExportFilterSql.Replaced(x)} THEN 1 ELSE 0 END), 0),
ifnull(SUM(CASE WHEN {ExportFilterSql.Failed(x)} AND NOT {ExportFilterSql.Copied(x)} THEN 1 ELSE 0 END), 0)
FROM media m JOIN entry e ON e.id = m.entry_id
WHERE e.account_id = @a AND {ExportFilterSql.DueFile(x)}
""").With("@a", accountId);
using var r = command.ExecuteReader();
r.Read();
return new ExportAccountCounts(r.GetInt32(0), r.GetInt32(1), r.GetInt32(2), r.GetInt32(3));
},
ct);
}