Richiesta di Alberto (#59): decidere cosa scaricare prima, una Dashboard compatta come pagina iniziale da guardare mentre il motore lavora, e le miniature di ciò che è arrivato. - Dashboard (§7.9, §10.2): /dashboard è la pagina iniziale e la prima voce della barra; /, /attivita, «Ho finito» del browser, il riquadro di stato e il ritorno dopo l'accesso portano lì. In alto l'anteprima del browser sempre visibile, chiesta ogni secondo mentre il motore lavora (LiveBrowserPreview cattura al più un fotogramma al secondo), accanto cosa sta facendo e i quattro tetti; poi la striscia più bassa, la cronologia con le miniature e la coda ridotta alle prime righe con «Mostra tutta». Sotto i 1000 px una colonna sola. - Miniature della cronologia: /api/activity/arrived dà gli elementi che una ricetta ha salvato (account, inizio e fine della ricetta), chiesti solo quando la riga entra in vista, al più otto con «+N». Un clic apre un'anteprima leggera con foto o video senza audio, frecce fra i file della riga, Esc, «Apri nella Libreria» e «Apri l'account». - «Cosa scaricare prima» (§7.2, §6.5): ordine generale dei tipi in Impostazioni → Limiti e comportamento (trascinare, «Su» e «Giù», nota sulle storie che scadono), predefinito storie, evidenza, post, reel, taggati. Dopo il giro, il lavoro dovuto si estrae con il peso dell'account per il peso del tipo (16, 8, 4, 2, 1): pesa, non rende fisso. La coda dei file segue lo stesso ordine. - Prove: DownloadOrderTests (ordine, pesi, coda, motore con seme fisso: il primo tipo viene più spesso ma non sempre, il giro resta primo, un tipo senza lavoro non si visita), DashboardApiTests, una prova dell'interfaccia per / e /attivita. Non ancora fatto: ordine per account e segno del reel (serve una migrazione da concordare con E1), «Raggruppa i post» / «Tutte le foto», confronto con i mockup, revisione del resto della guida che nomina ancora Attività. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
286 lines
13 KiB
C#
286 lines
13 KiB
C#
using Febe.Core.Domain;
|
|
using Febe.Core.Storage;
|
|
using static Febe.Data.Stores.EntryMapping;
|
|
|
|
namespace Febe.Data.Stores;
|
|
|
|
internal sealed class MediaStore(FebeDatabase db) : IMediaStore
|
|
{
|
|
public Task<Media?> GetAsync(long mediaId, CancellationToken ct = default) =>
|
|
db.ReadAsync(
|
|
c =>
|
|
{
|
|
using var r = c.Command($"SELECT {MediaColumns} FROM media m WHERE m.id = @id").With("@id", mediaId).ExecuteReader();
|
|
return r.Read() ? ReadMedia(r) : null;
|
|
},
|
|
ct);
|
|
|
|
public Task<IReadOnlyList<Media>> ListByEntryAsync(long entryId, CancellationToken ct = default) =>
|
|
db.ReadAsync<IReadOnlyList<Media>>(c => ReadMediaOf(sql => c.Command(sql), entryId), ct);
|
|
|
|
public Task<IReadOnlyList<MediaLocation>> FindBySha256Async(string sha256, CancellationToken ct = default)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(sha256);
|
|
var key = sha256.Trim().ToLowerInvariant();
|
|
return db.ReadAsync<IReadOnlyList<MediaLocation>>(
|
|
c =>
|
|
{
|
|
using var r = c.Command($"""
|
|
SELECT {MediaColumns}, {EntryColumns}, a.username
|
|
FROM media m JOIN entry e ON e.id = m.entry_id JOIN account a ON a.id = e.account_id
|
|
WHERE m.sha256 = @h ORDER BY m.id
|
|
""").With("@h", key).ExecuteReader();
|
|
var list = new List<MediaLocation>();
|
|
while (r.Read())
|
|
{
|
|
list.Add(new MediaLocation(ReadMedia(r), ReadEntry(r, MediaColumnCount), r.GetString(MediaColumnCount + EntryColumnCount)));
|
|
}
|
|
|
|
return list;
|
|
},
|
|
ct);
|
|
}
|
|
|
|
public Task<IReadOnlyDictionary<string, long>> MapPathsAsync(long accountId, CancellationToken ct = default) =>
|
|
db.ReadAsync<IReadOnlyDictionary<string, long>>(
|
|
c =>
|
|
{
|
|
using var r = c.Command("""
|
|
SELECT m.relative_path, m.entry_id FROM media m JOIN entry e ON e.id = m.entry_id
|
|
WHERE e.account_id = @a AND m.relative_path IS NOT NULL
|
|
""").With("@a", accountId).ExecuteReader();
|
|
var map = new Dictionary<string, long>(StringComparer.Ordinal);
|
|
while (r.Read())
|
|
{
|
|
map[r.GetString(0)] = r.GetInt64(1);
|
|
}
|
|
|
|
return map;
|
|
},
|
|
ct);
|
|
|
|
public Task<IReadOnlyList<PerceptualHashRecord>> LoadPerceptualHashesAsync(CancellationToken ct = default) =>
|
|
db.ReadAsync<IReadOnlyList<PerceptualHashRecord>>(
|
|
c =>
|
|
{
|
|
// One pass over media in table order with a key lookup per row: CROSS JOIN keeps media as the outer loop
|
|
// and the unary + keeps SQLite off the phash and state indexes, which would turn the pass into random
|
|
// reads once ANALYZE statistics exist (several times slower on 200,000 files).
|
|
using var r = c.Command("""
|
|
SELECT m.id, e.account_id, m.phash FROM media m CROSS JOIN entry e ON e.id = m.entry_id
|
|
WHERE +m.phash IS NOT NULL AND +m.state IN ('Downloaded', 'Imported')
|
|
""").ExecuteReader();
|
|
var list = new List<PerceptualHashRecord>();
|
|
while (r.Read())
|
|
{
|
|
list.Add(new PerceptualHashRecord(r.GetInt64(0), r.GetInt64(1), unchecked((ulong)r.GetInt64(2))));
|
|
}
|
|
|
|
return list;
|
|
},
|
|
ct);
|
|
|
|
public Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, CancellationToken ct = default) =>
|
|
ListPendingAsync(limit, "(e.kind = 'Story') DESC", ct);
|
|
|
|
public Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, IReadOnlyList<EntryKind> kindOrder, CancellationToken ct = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(kindOrder);
|
|
|
|
// The names are those of the enum, never text from outside: the rank is written into the query.
|
|
var rank = new System.Text.StringBuilder("CASE e.kind");
|
|
for (var i = 0; i < kindOrder.Count; i++)
|
|
{
|
|
rank.Append(" WHEN '").Append(kindOrder[i].ToString()).Append("' THEN ").Append(i.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
|
}
|
|
|
|
rank.Append(" ELSE ").Append(kindOrder.Count.ToString(System.Globalization.CultureInfo.InvariantCulture)).Append(" END");
|
|
return ListPendingAsync(limit, rank.ToString(), ct);
|
|
}
|
|
|
|
private Task<IReadOnlyList<PendingDownload>> ListPendingAsync(int limit, string first, CancellationToken ct) =>
|
|
db.ReadAsync<IReadOnlyList<PendingDownload>>(
|
|
c =>
|
|
{
|
|
using var r = c.Command($"""
|
|
SELECT {MediaColumns}, e.account_id, e.kind, e.published_at, e.expires_at
|
|
FROM media m JOIN entry e ON e.id = m.entry_id
|
|
WHERE m.state = 'ToDownload' AND e.state <> 'Deleted'
|
|
ORDER BY {first}, e.expires_at IS NULL, e.expires_at, e.discovered_at, m.entry_id, m.position
|
|
LIMIT @limit
|
|
""").With("@limit", (long)Math.Clamp(limit, 1, 10_000)).ExecuteReader();
|
|
var list = new List<PendingDownload>();
|
|
while (r.Read())
|
|
{
|
|
var o = MediaColumnCount;
|
|
list.Add(new PendingDownload(ReadMedia(r), r.GetInt64(o), r.GetEnum<EntryKind>(o + 1), r.GetTime(o + 2), r.GetTimeOrNull(o + 3)));
|
|
}
|
|
|
|
return list;
|
|
},
|
|
ct);
|
|
|
|
public Task<int> CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default) =>
|
|
db.ReadAsync(
|
|
c =>
|
|
{
|
|
var command = accountId is { } a
|
|
? c.Command("""
|
|
SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id
|
|
WHERE m.state = 'ToDownload' AND e.state <> 'Deleted' AND e.account_id = @a
|
|
""").With("@a", a)
|
|
: c.Command("""
|
|
SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id
|
|
WHERE m.state = 'ToDownload' AND e.state <> 'Deleted'
|
|
""");
|
|
return (int)command.ScalarInt64();
|
|
},
|
|
ct);
|
|
|
|
public Task<bool> MarkStoredAsync(long mediaId, StoredFile file, MediaState state, DateTimeOffset at, CancellationToken ct = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(file);
|
|
if (!EntryStateRules.IsPresent(state))
|
|
{
|
|
throw new ArgumentException("Un file salvato è «scaricato» o «importato».", nameof(state));
|
|
}
|
|
|
|
return db.WriteAsync<bool>(
|
|
w =>
|
|
{
|
|
var entryId = EntryOf(w, mediaId);
|
|
|
|
// A deletion «ricordando la scelta» wins over a file that arrives afterwards.
|
|
var rows = w.Command("""
|
|
UPDATE media SET state = @state, relative_path = @path, bytes = @bytes, sha256 = @sha, phash = @phash,
|
|
width = COALESCE(@w, width), height = COALESCE(@h, height), duration_ms = COALESCE(@d, duration_ms),
|
|
has_thumbnail = @thumb, downloaded_at = @at, last_error = NULL, source_url = NULL, cover_url = NULL
|
|
WHERE id = @id AND state <> 'Deleted'
|
|
AND (SELECT e.state FROM entry e WHERE e.id = media.entry_id) <> 'Deleted'
|
|
""")
|
|
.With("@state", Sql.Enum(state))
|
|
.With("@path", file.RelativePath)
|
|
.With("@bytes", file.Bytes)
|
|
.With("@sha", file.Sha256.ToLowerInvariant())
|
|
.With("@phash", Sql.Hash(file.PerceptualHash))
|
|
.With("@w", Sql.Int(file.Width))
|
|
.With("@h", Sql.Int(file.Height))
|
|
.With("@d", Sql.Duration(file.Duration))
|
|
.With("@thumb", Sql.Bool(file.HasThumbnail))
|
|
.With("@at", Sql.Time(at))
|
|
.With("@id", mediaId)
|
|
.ExecuteNonQuery();
|
|
if (rows == 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
RecomputeState(w, entryId, at);
|
|
return true;
|
|
},
|
|
ct);
|
|
}
|
|
|
|
public Task MarkFailedAsync(long mediaId, MediaState state, string? error, DateTimeOffset at, CancellationToken ct = default)
|
|
{
|
|
if (state is not (MediaState.Failed or MediaState.Expired or MediaState.Skipped or MediaState.ToDownload))
|
|
{
|
|
throw new ArgumentException("Uno scaricamento non riuscito porta a «fallito», «scaduto», «saltato» o di nuovo «da scaricare».", nameof(state));
|
|
}
|
|
|
|
return db.WriteAsync(
|
|
w =>
|
|
{
|
|
var entryId = EntryOf(w, mediaId);
|
|
w.Command("UPDATE media SET state = @state, last_error = @error, attempts = attempts + 1 WHERE id = @id")
|
|
.With("@state", Sql.Enum(state))
|
|
.With("@error", Sql.Text(error))
|
|
.With("@id", mediaId)
|
|
.ExecuteNonQuery();
|
|
RecomputeState(w, entryId, at);
|
|
},
|
|
ct);
|
|
}
|
|
|
|
public Task<IReadOnlyList<Media>> AddToEntryAsync(long entryId, IReadOnlyList<Media> media, CancellationToken ct = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(media);
|
|
if (media.Any(m => m.Position < 1))
|
|
{
|
|
throw new ArgumentException("Le posizioni dei file partono da 1.", nameof(media));
|
|
}
|
|
|
|
return db.WriteAsync<IReadOnlyList<Media>>(
|
|
w =>
|
|
{
|
|
if (ReadEntryById(w.Command, entryId) is null)
|
|
{
|
|
throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
|
|
}
|
|
|
|
var present = ReadMediaOf(w.Command, entryId).Select(m => m.Position).ToHashSet();
|
|
foreach (var file in media.OrderBy(m => m.Position).Where(m => present.Add(m.Position)))
|
|
{
|
|
var command = w.Command(InsertMediaSql);
|
|
BindMedia(command, file with { EntryId = entryId, Sha256 = file.Sha256?.ToLowerInvariant(), InstagramId = NormalizeId(file.InstagramId) });
|
|
command.ExecuteNonQuery();
|
|
}
|
|
|
|
RecomputeState(w, entryId);
|
|
return ReadMediaOf(w.Command, entryId);
|
|
},
|
|
ct);
|
|
}
|
|
|
|
public Task UpdateSourceAsync(long mediaId, string? sourceUrl, string? coverUrl, DateTimeOffset seenAt, CancellationToken ct = default) =>
|
|
db.WriteAsync(
|
|
w =>
|
|
{
|
|
var entryId = EntryOf(w, mediaId);
|
|
w.Command("""
|
|
UPDATE media SET source_url = @u, cover_url = COALESCE(@c, cover_url), source_seen_at = @at,
|
|
state = CASE WHEN state IN ('Expired', 'Failed') THEN 'ToDownload' ELSE state END
|
|
WHERE id = @id
|
|
""")
|
|
.With("@u", Sql.Text(sourceUrl))
|
|
.With("@c", Sql.Text(coverUrl))
|
|
.With("@at", Sql.Time(seenAt))
|
|
.With("@id", mediaId)
|
|
.ExecuteNonQuery();
|
|
RecomputeState(w, entryId);
|
|
},
|
|
ct);
|
|
|
|
public Task SetThumbnailAsync(long mediaId, bool hasThumbnail, CancellationToken ct = default) =>
|
|
db.WriteAsync(
|
|
w => w.Command("UPDATE media SET has_thumbnail = @t WHERE id = @id").With("@t", Sql.Bool(hasThumbnail)).With("@id", mediaId).ExecuteNonQuery(),
|
|
ct);
|
|
|
|
public Task UpdateAsync(Media media, CancellationToken ct = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(media);
|
|
return db.WriteAsync(
|
|
w =>
|
|
{
|
|
var entryId = EntryOf(w, media.Id);
|
|
var command = w.Command("""
|
|
UPDATE media SET position = @position, kind = @kind, instagram_id = @instagram_id, width = @width, height = @height,
|
|
duration_ms = @duration_ms, state = @state, relative_path = @relative_path, bytes = @bytes, sha256 = @sha256,
|
|
phash = @phash, has_thumbnail = @has_thumbnail, source_url = @source_url, cover_url = @cover_url,
|
|
source_seen_at = @source_seen_at, attempts = @attempts, last_error = @last_error, downloaded_at = @downloaded_at
|
|
WHERE id = @id
|
|
""");
|
|
BindMedia(command, media with { EntryId = entryId });
|
|
command.With("@id", media.Id).ExecuteNonQuery();
|
|
RecomputeState(w, entryId, media.DownloadedAt);
|
|
},
|
|
ct);
|
|
}
|
|
|
|
private static long EntryOf(WriteContext w, long mediaId)
|
|
{
|
|
var value = w.Command("SELECT entry_id FROM media WHERE id = @id").With("@id", mediaId).ExecuteScalar();
|
|
return value is long entryId ? entryId : throw new KeyNotFoundException($"File {mediaId} non trovato.");
|
|
}
|
|
}
|