Merge branch 'w2/raccolta' into febe-v1
This commit is contained in:
74 files changed
+12689
-13
No files matched your search
@@ -0,0 +1,489 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Pacing;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Collection.Downloads;
|
||||
|
||||
/// <summary>Options of the download queue (spec §6.5).</summary>
|
||||
public sealed record DownloadOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Folder for the temporary copy of a file while it downloads (under Dati, never the library). A partial download
|
||||
/// never leaves a file with its final name (spec §6.5 point 4).
|
||||
/// </summary>
|
||||
public required string StagingFolder { get; init; }
|
||||
|
||||
/// <summary>At most two downloads at the same time (spec §6.5 point 6).</summary>
|
||||
public int MaxConcurrent { get; init; } = 2;
|
||||
|
||||
/// <summary>Small random pause after each file.</summary>
|
||||
public TimeSpan PauseMin { get; init; } = TimeSpan.FromMilliseconds(400);
|
||||
|
||||
public TimeSpan PauseMax { get; init; } = TimeSpan.FromSeconds(3);
|
||||
|
||||
/// <summary>
|
||||
/// HTTP statuses that mean «the signed address expired». 403 and 410 for the test site; for the real CDN they are
|
||||
/// a hypothesis to confirm with H7 in M0.
|
||||
/// </summary>
|
||||
public IReadOnlySet<int> ExpiredStatuses { get; init; } = new HashSet<int> { 403, 410 };
|
||||
|
||||
/// <summary>After this many failed attempts a file is «fallito».</summary>
|
||||
public int MaxAttempts { get; init; } = 5;
|
||||
|
||||
/// <summary>How many pending files are read from the database at a time.</summary>
|
||||
public int BatchSize { get; init; } = 200;
|
||||
|
||||
/// <summary>When idle, how long to wait before looking at the database again (a <see cref="DownloadQueue.Wake"/> ends it earlier).</summary>
|
||||
public TimeSpan IdlePoll { get; init; } = TimeSpan.FromMinutes(1);
|
||||
}
|
||||
|
||||
/// <summary>What one pass of the queue did.</summary>
|
||||
public sealed record DownloadReport(int Stored, int Duplicates, int Skipped, int Expired, int Failed, int Retried, long Bytes, bool BudgetReached)
|
||||
{
|
||||
public int Total => Stored + Duplicates + Skipped + Expired + Failed + Retried;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The download queue (spec §6.5): files waiting in the database, stories first (they expire), at most two at the
|
||||
/// same time with small random pauses, inside the daily data budget. Each file goes through <see cref="IFileFetcher"/>
|
||||
/// (the browser, <c>Network.loadNetworkResource</c>) into a temporary file and then into the library through
|
||||
/// <see cref="LibraryIngest"/> (final name, SHA-256, duplicates of §9.5). The account's settings apply: video size
|
||||
/// limit and «video delle storie» (skipped files become «saltato»). An expired address sends the file back to wait
|
||||
/// and queues «Post singolo» — never for stories, which cannot be recovered.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It talks only to the CDN, never to the site, so it keeps working while the circuit breaker stops the site
|
||||
/// (spec §7.6). The <c>HttpClient</c> fallback of §6.5 point 3 is deliberately not implemented: it stays behind
|
||||
/// <see cref="IFileFetcher"/> until H7 says whether it is needed (decision in docs/decisioni.md).
|
||||
/// Addresses are never logged.
|
||||
/// </remarks>
|
||||
public sealed class DownloadQueue
|
||||
{
|
||||
private readonly IFebeStorage _storage;
|
||||
private readonly LibraryIngest _ingest;
|
||||
private readonly IFileFetcher _fetcher;
|
||||
private readonly IDataBudget _budget;
|
||||
private readonly IClock _clock;
|
||||
private readonly IRandomSource _random;
|
||||
private readonly DownloadOptions _options;
|
||||
private readonly CollectionWriter _writer;
|
||||
private readonly SemaphoreSlim _wake = new(0, int.MaxValue);
|
||||
private readonly Lock _randomGate = new();
|
||||
|
||||
public DownloadQueue(IFebeStorage storage, LibraryIngest ingest, IFileFetcher fetcher, IDataBudget budget, IClock clock, IRandomSource random, DownloadOptions options)
|
||||
{
|
||||
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
|
||||
_ingest = ingest ?? throw new ArgumentNullException(nameof(ingest));
|
||||
_fetcher = fetcher ?? throw new ArgumentNullException(nameof(fetcher));
|
||||
_budget = budget ?? throw new ArgumentNullException(nameof(budget));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_random = random ?? throw new ArgumentNullException(nameof(random));
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
if (_options.MaxConcurrent is < 1 or > 2)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(options), "Al massimo due scaricamenti insieme (specifica §6.5).");
|
||||
}
|
||||
|
||||
_writer = new CollectionWriter(storage, clock);
|
||||
}
|
||||
|
||||
/// <summary>Raised after each file, for the interface (no addresses).</summary>
|
||||
public event EventHandler<DownloadProgress>? Progress;
|
||||
|
||||
/// <summary>New files are waiting: ends the idle wait of <see cref="RunAsync"/>.</summary>
|
||||
public void Wake() => _wake.Release();
|
||||
|
||||
/// <summary>Works until cancelled: a pass over the waiting files, then an idle wait.</summary>
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
var report = await RunOnceAsync(ct).ConfigureAwait(false);
|
||||
var wait = report.BudgetReached ? TimeSpan.FromMinutes(30) : _options.IdlePoll;
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var woken = _wake.WaitAsync(linked.Token);
|
||||
var slept = _clock.Delay(wait, linked.Token);
|
||||
await Task.WhenAny(woken, slept).ConfigureAwait(false);
|
||||
await linked.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(woken, slept).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One pass: downloads what is waiting until nothing is left or the data budget is reached.</summary>
|
||||
public async Task<DownloadReport> RunOnceAsync(CancellationToken ct)
|
||||
{
|
||||
Directory.CreateDirectory(_options.StagingFolder);
|
||||
var tally = new Tally();
|
||||
var attempted = new ConcurrentDictionary<long, bool>();
|
||||
var accounts = new ConcurrentDictionary<long, Account?>();
|
||||
var singlePostQueued = new ConcurrentDictionary<long, bool>();
|
||||
while (!ct.IsCancellationRequested && !tally.BudgetReached)
|
||||
{
|
||||
var batch = (await _storage.Media.ListPendingDownloadsAsync(_options.BatchSize, ct).ConfigureAwait(false))
|
||||
.Where(p => p.Media.SourceUrl is not null && !attempted.ContainsKey(p.Media.Id))
|
||||
.ToList();
|
||||
if (batch.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var queue = new ConcurrentQueue<PendingDownload>(batch);
|
||||
var workers = Enumerable.Range(0, _options.MaxConcurrent).Select(_ => Task.Run(
|
||||
async () =>
|
||||
{
|
||||
while (!tally.BudgetReached && queue.TryDequeue(out var pending))
|
||||
{
|
||||
attempted[pending.Media.Id] = true;
|
||||
await ProcessAsync(pending, tally, accounts, singlePostQueued, ct).ConfigureAwait(false);
|
||||
await _clock.Delay(DrawPause(), ct).ConfigureAwait(false);
|
||||
}
|
||||
},
|
||||
ct)).ToList();
|
||||
await Task.WhenAll(workers).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return tally.ToReport();
|
||||
}
|
||||
|
||||
private TimeSpan DrawPause()
|
||||
{
|
||||
lock (_randomGate)
|
||||
{
|
||||
return _random.Between(_options.PauseMin, _options.PauseMax);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ProcessAsync(PendingDownload pending, Tally tally, ConcurrentDictionary<long, Account?> accounts, ConcurrentDictionary<long, bool> singlePostQueued, CancellationToken ct)
|
||||
{
|
||||
var media = pending.Media;
|
||||
if (!accounts.TryGetValue(pending.AccountId, out var account))
|
||||
{
|
||||
account = await _storage.Accounts.GetAsync(pending.AccountId, ct).ConfigureAwait(false);
|
||||
accounts[pending.AccountId] = account;
|
||||
}
|
||||
|
||||
var entry = await _storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false);
|
||||
if (account is null || entry is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (CollectionWriter.SkipReason(account, entry.Kind, media.Kind) is { } reason)
|
||||
{
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, reason, _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Skipped);
|
||||
Report(media, entry, DownloadStep.Skipped);
|
||||
return;
|
||||
}
|
||||
|
||||
if (await _budget.RemainingTodayAsync(ct).ConfigureAwait(false) <= 0)
|
||||
{
|
||||
tally.BudgetReached = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Uri.TryCreate(media.SourceUrl, UriKind.Absolute, out var address))
|
||||
{
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, "Indirizzo del file non valido.", _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Failed);
|
||||
return;
|
||||
}
|
||||
|
||||
var maxBytes = media.Kind == MediaKind.Video ? account.Limits.MaxVideoBytes : null;
|
||||
var temp = Path.Combine(_options.StagingFolder, $"{SafeFileWriter.TempPrefix}{Guid.NewGuid():N}{SafeFileWriter.TempSuffix}");
|
||||
try
|
||||
{
|
||||
FetchResult result;
|
||||
await using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true))
|
||||
{
|
||||
result = await _fetcher.FetchAsync(address, file, new FetchOptions(maxBytes), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (result.Bytes > 0)
|
||||
{
|
||||
await _budget.RecordAsync(result.Bytes, account.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
tally.AddBytes(result.Bytes);
|
||||
}
|
||||
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case FetchOutcome.Completed:
|
||||
await IngestAsync(account, entry, media, temp, maxBytes, tally, ct).ConfigureAwait(false);
|
||||
return;
|
||||
case FetchOutcome.TooLarge:
|
||||
var limit = maxBytes is { } m ? ItalianText.Number(Math.Max(1, m / (1024 * 1024))) : "?";
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, $"Video oltre il limite di {limit} MB impostato per l'account.", _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Skipped);
|
||||
Report(media, entry, DownloadStep.Skipped);
|
||||
return;
|
||||
case FetchOutcome.HttpError when result.HttpStatus is { } status && _options.ExpiredStatuses.Contains(status):
|
||||
await ExpiredAsync(entry, media, tally, singlePostQueued, ct).ConfigureAwait(false);
|
||||
return;
|
||||
case FetchOutcome.HostNotAllowed:
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, "L'indirizzo non è del CDN: non si scarica (specifica §6.5).", _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Failed);
|
||||
Report(media, entry, DownloadStep.Failed);
|
||||
return;
|
||||
default:
|
||||
var error = result.HttpStatus is { } code
|
||||
? $"Il CDN ha risposto {code.ToString(CultureInfo.InvariantCulture)}."
|
||||
: $"Errore di rete durante lo scaricamento ({result.Error ?? "senza dettagli"}).";
|
||||
if (media.Attempts + 1 >= _options.MaxAttempts)
|
||||
{
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, error, _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Failed);
|
||||
Report(media, entry, DownloadStep.Failed);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.ToDownload, error, _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Retried);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (FileTooLargeException)
|
||||
{
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, "Video oltre il limite impostato per l'account.", _clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Skipped);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
// Disk full or similar: the file waits for the next pass (nothing was written under the final name).
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.ToDownload, $"Scrittura non riuscita: {ex.GetType().Name}.", _clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Retried);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDelete(temp);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task IngestAsync(Account account, Entry entry, Media media, string temp, long? maxBytes, Tally tally, CancellationToken ct)
|
||||
{
|
||||
MemoryStream? cover = null;
|
||||
try
|
||||
{
|
||||
if (media.Kind == MediaKind.Video && Uri.TryCreate(media.CoverUrl, UriKind.Absolute, out var coverAddress))
|
||||
{
|
||||
var buffer = new MemoryStream();
|
||||
var fetched = await _fetcher.FetchAsync(coverAddress, buffer, new FetchOptions(8L * 1024 * 1024), ct).ConfigureAwait(false);
|
||||
if (fetched.Bytes > 0)
|
||||
{
|
||||
await _budget.RecordAsync(fetched.Bytes, account.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
tally.AddBytes(fetched.Bytes);
|
||||
}
|
||||
|
||||
if (fetched.Succeeded)
|
||||
{
|
||||
buffer.Position = 0;
|
||||
cover = buffer;
|
||||
}
|
||||
else
|
||||
{
|
||||
await buffer.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var highlightTitle = entry.Kind == EntryKind.Highlight
|
||||
? (await _storage.Highlights.ListForEntryAsync(entry.Id, ct).ConfigureAwait(false)).OrderBy(h => h.Position).FirstOrDefault()?.Title
|
||||
: null;
|
||||
MediaSaveResult saved;
|
||||
await using (var content = new FileStream(temp, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true))
|
||||
{
|
||||
saved = await _ingest.SaveMediaAsync(
|
||||
account,
|
||||
entry,
|
||||
media,
|
||||
new MediaContent { Content = content, Extension = Extension(temp, media), Cover = cover, MaxBytes = maxBytes },
|
||||
highlightTitle,
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (saved.Outcome == MediaSaveOutcome.Stored)
|
||||
{
|
||||
tally.Add(ref tally.Stored);
|
||||
Report(media, entry, DownloadStep.Stored);
|
||||
await AppendJournalWhenCompleteAsync(entry, ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await IdenticalAsync(entry, media, saved.Identical!, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Duplicates);
|
||||
Report(media, entry, DownloadStep.Duplicate);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (cover is not null)
|
||||
{
|
||||
await cover.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// §9.5: the file just downloaded is identical to one already in the same account. The new file is discarded
|
||||
/// before entering the library. When the existing file belongs to an imported entry without Instagram data, that
|
||||
/// entry takes the data and the new record goes away; otherwise the new file is settled as «saltato» with a note.
|
||||
/// </summary>
|
||||
private async Task IdenticalAsync(Entry entry, Media media, MediaLocation existing, CancellationToken ct)
|
||||
{
|
||||
var files = await _storage.Media.ListByEntryAsync(entry.Id, ct).ConfigureAwait(false);
|
||||
if (existing.Entry.InstagramId is null && existing.Entry.Kind == entry.Kind && files.Count == 1)
|
||||
{
|
||||
await _storage.Entries.RemoveAsync(entry.Id, ct).ConfigureAwait(false);
|
||||
await _storage.Entries.UpdateAsync(
|
||||
existing.Entry with
|
||||
{
|
||||
InstagramId = entry.InstagramId,
|
||||
Code = existing.Entry.Code ?? entry.Code,
|
||||
Caption = existing.Entry.Caption ?? entry.Caption,
|
||||
AuthorUsername = existing.Entry.AuthorUsername ?? entry.AuthorUsername,
|
||||
AuthorInstagramId = existing.Entry.AuthorInstagramId ?? entry.AuthorInstagramId,
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
await _writer.EventAsync("file-gia-in-libreria", "Un file appena scaricato era già in libreria fra quelli importati: non è stato copiato di nuovo, all'elemento esistente sono stati aggiunti i dati di Instagram.", EventSeverity.Info, entry.AccountId, null, ct).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, "Identico a un file già presente nell'account: non copiato di nuovo.", _clock.Now, ct).ConfigureAwait(false);
|
||||
if (existing.Entry.Caption is null && entry.Caption is not null && existing.Entry.Provenance == Provenance.Imported)
|
||||
{
|
||||
await _storage.Entries.UpdateAsync(existing.Entry with { Caption = entry.Caption }, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An expired address: back to wait and «Post singolo» queued; stories cannot be recovered (§6.5 point 5).</summary>
|
||||
private async Task ExpiredAsync(Entry entry, Media media, Tally tally, ConcurrentDictionary<long, bool> singlePostQueued, CancellationToken ct)
|
||||
{
|
||||
if (entry.Kind is EntryKind.Story or EntryKind.Highlight or EntryKind.ProfilePicture)
|
||||
{
|
||||
var why = entry.Kind == EntryKind.Story
|
||||
? "Indirizzo scaduto: per le storie non c'è recupero dopo la scadenza."
|
||||
: "Indirizzo scaduto: si rinnova alla prossima lettura del profilo.";
|
||||
await _storage.Media.MarkFailedAsync(media.Id, entry.Kind == EntryKind.Story ? MediaState.Failed : MediaState.Expired, why, _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Expired);
|
||||
Report(media, entry, DownloadStep.Expired);
|
||||
return;
|
||||
}
|
||||
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Expired, "Indirizzo scaduto: lo rinnova «Post singolo».", _clock.Now, ct).ConfigureAwait(false);
|
||||
if (singlePostQueued.TryAdd(entry.Id, true))
|
||||
{
|
||||
await _writer.QueueSinglePostAsync(entry, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
tally.Add(ref tally.Expired);
|
||||
Report(media, entry, DownloadStep.Expired);
|
||||
}
|
||||
|
||||
private async Task AppendJournalWhenCompleteAsync(Entry entry, CancellationToken ct)
|
||||
{
|
||||
var files = await _storage.Media.ListByEntryAsync(entry.Id, ct).ConfigureAwait(false);
|
||||
if (files.All(f => f.State is not (MediaState.ToDownload or MediaState.Expired)))
|
||||
{
|
||||
await _ingest.AppendJournalAsync(entry.Id, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void Report(Media media, Entry entry, DownloadStep step) =>
|
||||
Progress?.Invoke(this, new DownloadProgress(media.Id, entry.Id, entry.AccountId, entry.Kind, step));
|
||||
|
||||
/// <summary>The extension from the content (magic numbers), else from the kind of file.</summary>
|
||||
private static string Extension(string path, Media media)
|
||||
{
|
||||
Span<byte> head = stackalloc byte[12];
|
||||
using (var stream = File.OpenRead(path))
|
||||
{
|
||||
var read = stream.Read(head);
|
||||
head = head[..read];
|
||||
}
|
||||
|
||||
if (head.Length >= 3 && head[0] == 0xFF && head[1] == 0xD8 && head[2] == 0xFF)
|
||||
{
|
||||
return ".jpg";
|
||||
}
|
||||
|
||||
if (head.Length >= 8 && head[0] == 0x89 && head[1] == (byte)'P' && head[2] == (byte)'N' && head[3] == (byte)'G')
|
||||
{
|
||||
return ".png";
|
||||
}
|
||||
|
||||
if (head.Length >= 12 && head[..4].SequenceEqual("RIFF"u8) && head[8..12].SequenceEqual("WEBP"u8))
|
||||
{
|
||||
return ".webp";
|
||||
}
|
||||
|
||||
if (head.Length >= 12 && head[4..8].SequenceEqual("ftyp"u8))
|
||||
{
|
||||
return head[8..12].SequenceEqual("heic"u8) || head[8..12].SequenceEqual("heix"u8) ? ".heic" : ".mp4";
|
||||
}
|
||||
|
||||
return media.Kind == MediaKind.Video ? ".mp4" : ".jpg";
|
||||
}
|
||||
|
||||
private static void TryDelete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Tally
|
||||
{
|
||||
public int Stored;
|
||||
public int Duplicates;
|
||||
public int Skipped;
|
||||
public int Expired;
|
||||
public int Failed;
|
||||
public int Retried;
|
||||
private long _bytes;
|
||||
private volatile bool _budgetReached;
|
||||
|
||||
public bool BudgetReached
|
||||
{
|
||||
get => _budgetReached;
|
||||
set => _budgetReached = value;
|
||||
}
|
||||
|
||||
public void Add(ref int counter) => Interlocked.Increment(ref counter);
|
||||
|
||||
public void AddBytes(long bytes) => Interlocked.Add(ref _bytes, bytes);
|
||||
|
||||
public DownloadReport ToReport() =>
|
||||
new(Stored, Duplicates, Skipped, Expired, Failed, Retried, Interlocked.Read(ref _bytes), BudgetReached);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>How a file of the queue ended.</summary>
|
||||
public enum DownloadStep
|
||||
{
|
||||
Stored,
|
||||
Duplicate,
|
||||
Skipped,
|
||||
Expired,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>Progress of the queue for the interface: identifiers only, never addresses.</summary>
|
||||
public sealed record DownloadProgress(long MediaId, long EntryId, long AccountId, EntryKind Kind, DownloadStep Step);
|
||||
@@ -0,0 +1,22 @@
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// What the recipes need from the stop-signal detection (spec §7.6): to know when a signal was raised, and to report
|
||||
/// what only they can tell (empty pages, the session cookie). Implemented by <see cref="SignalDetector"/>.
|
||||
/// </summary>
|
||||
public interface IStopSignals
|
||||
{
|
||||
/// <summary>Raised after a signal has been reported to the circuit breaker.</summary>
|
||||
event EventHandler<Signal>? SignalRaised;
|
||||
|
||||
/// <summary>A page (or page of data) turned out empty; repeated empty pages raise a throttle signal.</summary>
|
||||
Signal? ObserveEmptyPage(string? url = null);
|
||||
|
||||
/// <summary>A page with content: resets the empty-page counter.</summary>
|
||||
void ObserveNonEmptyPage();
|
||||
|
||||
/// <summary>Result of the session-cookie check: a missing cookie is a disconnection.</summary>
|
||||
Signal? ObserveSessionCookie(bool present);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Febe.Core.Collection.Readers;
|
||||
|
||||
/// <summary>
|
||||
/// Describes the key structure of a JSON response without any value (spec §6.4: «formato non riconosciuto» events
|
||||
/// carry only the structure). Keys that look like identifiers become «#», so not even they leak.
|
||||
/// </summary>
|
||||
/// <remarks>Example: <c>{dati:{elenco:[{a,b,c:{d}}]},stato}</c>.</remarks>
|
||||
public static class KeyStructure
|
||||
{
|
||||
public const int DefaultMaxLength = 600;
|
||||
private const int MaxDepth = 6;
|
||||
private const int MaxKeysPerObject = 24;
|
||||
|
||||
public static string Describe(JsonElement root, int maxLength = DefaultMaxLength)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
Append(sb, root, 0);
|
||||
if (sb.Length > maxLength)
|
||||
{
|
||||
sb.Length = Math.Max(0, maxLength - 1);
|
||||
sb.Append('…');
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True for keys that look like identifiers rather than names: long digit runs, long hexadecimal or mixed
|
||||
/// letter-digit tokens. Shared with the sample sanitizer (spec §14.5).
|
||||
/// </summary>
|
||||
public static bool LooksLikeIdentifier(string key)
|
||||
{
|
||||
if (string.IsNullOrEmpty(key))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var digits = 0;
|
||||
var letters = 0;
|
||||
var others = 0;
|
||||
foreach (var c in key)
|
||||
{
|
||||
if (char.IsAsciiDigit(c))
|
||||
{
|
||||
digits++;
|
||||
}
|
||||
else if (char.IsAsciiLetter(c))
|
||||
{
|
||||
letters++;
|
||||
}
|
||||
else if (c is not ('_' or '-'))
|
||||
{
|
||||
others++;
|
||||
}
|
||||
}
|
||||
|
||||
if (digits >= 5 && letters == 0 && others == 0)
|
||||
{
|
||||
return true; // 17841400000, 1234567
|
||||
}
|
||||
|
||||
if (others == 0 && key.Length >= 16 && digits >= 3 && letters >= 3)
|
||||
{
|
||||
return true; // tokens and hashes
|
||||
}
|
||||
|
||||
return others > 0 && digits >= 5; // e.g. «id:123456»
|
||||
}
|
||||
|
||||
private static void Append(StringBuilder sb, JsonElement element, int depth)
|
||||
{
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
if (depth >= MaxDepth)
|
||||
{
|
||||
sb.Append("{…}");
|
||||
return;
|
||||
}
|
||||
|
||||
sb.Append('{');
|
||||
var count = 0;
|
||||
var identifierKeys = 0;
|
||||
JsonElement? identifierSample = null;
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (LooksLikeIdentifier(property.Name))
|
||||
{
|
||||
identifierKeys++;
|
||||
identifierSample ??= property.Value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (count == MaxKeysPerObject)
|
||||
{
|
||||
sb.Append(",…");
|
||||
count++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (count > MaxKeysPerObject)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (count > 0)
|
||||
{
|
||||
sb.Append(',');
|
||||
}
|
||||
|
||||
sb.Append(property.Name);
|
||||
if (property.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
|
||||
{
|
||||
sb.Append(':');
|
||||
Append(sb, property.Value, depth + 1);
|
||||
}
|
||||
|
||||
count++;
|
||||
}
|
||||
|
||||
if (identifierKeys > 0)
|
||||
{
|
||||
if (count > 0)
|
||||
{
|
||||
sb.Append(',');
|
||||
}
|
||||
|
||||
sb.Append('#');
|
||||
if (identifierSample is { ValueKind: JsonValueKind.Object or JsonValueKind.Array } sample)
|
||||
{
|
||||
sb.Append(':');
|
||||
Append(sb, sample, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
sb.Append('}');
|
||||
return;
|
||||
case JsonValueKind.Array:
|
||||
if (depth >= MaxDepth)
|
||||
{
|
||||
sb.Append("[…]");
|
||||
return;
|
||||
}
|
||||
|
||||
sb.Append('[');
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
if (item.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
|
||||
{
|
||||
Append(sb, item, depth + 1);
|
||||
}
|
||||
|
||||
break; // the first element stands for the others
|
||||
}
|
||||
|
||||
sb.Append(']');
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Collection.Readers;
|
||||
|
||||
/// <summary>Turns what the reader recognized into domain records (spec §6.4: Entry, Media, Account, Highlight).</summary>
|
||||
public static class ReadMapping
|
||||
{
|
||||
/// <summary>The entry of a content item for an account.</summary>
|
||||
/// <param name="item">The content.</param>
|
||||
/// <param name="accountId">Local key of the account the entry belongs to (for tagged posts: the tagged account).</param>
|
||||
/// <param name="kind">Post, story, highlight item or tagged post.</param>
|
||||
/// <param name="now">Discovery time.</param>
|
||||
public static Entry ToEntry(ContentItem item, long accountId, EntryKind kind, DateTimeOffset now)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
var foreignAuthor = kind == EntryKind.Tagged;
|
||||
return new Entry
|
||||
{
|
||||
AccountId = accountId,
|
||||
Kind = kind,
|
||||
InstagramId = item.Id,
|
||||
Code = item.Code,
|
||||
PublishedAt = item.TakenAt,
|
||||
Caption = item.Caption,
|
||||
AuthorUsername = foreignAuthor ? item.Owner?.Username : null,
|
||||
AuthorInstagramId = foreignAuthor ? item.Owner?.Id : null,
|
||||
DiscoveredAt = now,
|
||||
ExpiresAt = kind == EntryKind.Story ? item.ExpiresAt ?? item.TakenAt.AddHours(24) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The files of a content item, positions from 1, with the addresses of the chosen versions.</summary>
|
||||
public static IReadOnlyList<Media> ToMedia(ContentItem item, DateTimeOffset now)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
return [.. item.Files.Select((file, index) => ToMedia(file, index + 1, now))];
|
||||
}
|
||||
|
||||
public static Media ToMedia(ContentFile file, int position, DateTimeOffset now)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(file);
|
||||
return new Media
|
||||
{
|
||||
Position = position,
|
||||
Kind = file.Kind,
|
||||
InstagramId = file.InstagramId,
|
||||
Width = file.Best.Width,
|
||||
Height = file.Best.Height,
|
||||
Duration = file.Duration,
|
||||
SourceUrl = file.Best.Url,
|
||||
CoverUrl = file.Cover?.Url,
|
||||
SourceSeenAt = now,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A profile picture as an entry: its identity is the address path of the picture (it changes with the picture).</summary>
|
||||
public static (Entry Entry, Media Media)? ToProfilePicture(ProfileInfo profile, long accountId, DateTimeOffset now)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
if (profile.Picture is not { } picture || !Uri.TryCreate(picture.Url, UriKind.Absolute, out var uri))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var identity = "ritratto-" + Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(uri.AbsolutePath)))[..16];
|
||||
var entry = new Entry
|
||||
{
|
||||
AccountId = accountId,
|
||||
Kind = EntryKind.ProfilePicture,
|
||||
InstagramId = identity,
|
||||
PublishedAt = now,
|
||||
DiscoveredAt = now,
|
||||
};
|
||||
var media = new Media
|
||||
{
|
||||
Position = 1,
|
||||
Kind = MediaKind.Photo,
|
||||
Width = picture.Width,
|
||||
Height = picture.Height,
|
||||
SourceUrl = picture.Url,
|
||||
SourceSeenAt = now,
|
||||
};
|
||||
return (entry, media);
|
||||
}
|
||||
|
||||
public static Highlight ToHighlight(HighlightInfo info, long accountId, int position, DateTimeOffset now)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(info);
|
||||
return new Highlight
|
||||
{
|
||||
AccountId = accountId,
|
||||
InstagramId = info.Id,
|
||||
Title = string.IsNullOrWhiteSpace(info.Title) ? "Senza titolo" : info.Title.Trim(),
|
||||
Position = position,
|
||||
DiscoveredAt = now,
|
||||
LastCheckedAt = now,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System.Text;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Collection.Readers;
|
||||
|
||||
/// <summary>One version of a file as the page received it: an address with its size.</summary>
|
||||
/// <param name="Url">Signed address: never logged (spec §13.2).</param>
|
||||
/// <param name="Width">Width in pixels, when given.</param>
|
||||
/// <param name="Height">Height in pixels, when given.</param>
|
||||
/// <param name="HasAudio">For videos: whether the rendition carries audio; null when the response does not say.</param>
|
||||
public sealed record FileVersion(string Url, int? Width, int? Height, bool? HasAudio)
|
||||
{
|
||||
public long Area => (long)(Width ?? 0) * (Height ?? 0);
|
||||
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Width = {Width}, Height = {Height}, HasAudio = {HasAudio}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One file of a content item, with the version chosen for download (spec §6.5 point 1).</summary>
|
||||
/// <param name="Kind">Photo or video.</param>
|
||||
/// <param name="InstagramId">Identifier of this file of a series, when the site gives one.</param>
|
||||
/// <param name="Best">Largest image, or best video version complete with audio.</param>
|
||||
/// <param name="Cover">For videos: the largest cover image.</param>
|
||||
/// <param name="Duration">Video duration, when given.</param>
|
||||
public sealed record ContentFile(MediaKind Kind, string? InstagramId, FileVersion Best, FileVersion? Cover, TimeSpan? Duration);
|
||||
|
||||
/// <summary>A profile as it appears in a response (author of content, profile page, list of followed profiles).</summary>
|
||||
public sealed record ProfileInfo
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
|
||||
public required string Username { get; init; }
|
||||
|
||||
public string? DisplayName { get; init; }
|
||||
|
||||
public bool? IsPrivate { get; init; }
|
||||
|
||||
public bool? IsFollowed { get; init; }
|
||||
|
||||
public int? PostCount { get; init; }
|
||||
|
||||
/// <summary>Largest version of the profile picture.</summary>
|
||||
public FileVersion? Picture { get; init; }
|
||||
|
||||
/// <summary>Publication time of the latest active story (stories bar).</summary>
|
||||
public DateTimeOffset? LatestStoryAt { get; init; }
|
||||
|
||||
/// <summary>True when the response presents this profile as the connected account (H10).</summary>
|
||||
public bool IsViewer { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A content node: a post, a story or an item of a highlight collection.</summary>
|
||||
public sealed record ContentItem
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
|
||||
public string? Code { get; init; }
|
||||
|
||||
public required DateTimeOffset TakenAt { get; init; }
|
||||
|
||||
/// <summary>Caption: never logged.</summary>
|
||||
public string? Caption { get; init; }
|
||||
|
||||
public ProfileInfo? Owner { get; init; }
|
||||
|
||||
public bool Pinned { get; init; }
|
||||
|
||||
public DateTimeOffset? ExpiresAt { get; init; }
|
||||
|
||||
/// <summary>The files in order (one for a single photo or video, several for a series).</summary>
|
||||
public required IReadOnlyList<ContentFile> Files { get; init; }
|
||||
|
||||
/// <summary>False when the series declares more files than the response carries: Post singolo completes it.</summary>
|
||||
public bool IsComplete { get; init; } = true;
|
||||
|
||||
/// <summary>Identifier of the highlight collection the item was found in, if any.</summary>
|
||||
public string? HighlightId { get; init; }
|
||||
|
||||
/// <summary>Order of appearance in the response, from 0.</summary>
|
||||
public int Order { get; init; }
|
||||
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Id = {Id}, Code = {Code}, TakenAt = {TakenAt:O}, Owner = {Owner?.Username}, Pinned = {Pinned}, Files = {Files.Count}, IsComplete = {IsComplete}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A highlight collection, with its contents when the response carries them.</summary>
|
||||
public sealed record HighlightInfo
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
|
||||
public required string Title { get; init; }
|
||||
|
||||
public ProfileInfo? Owner { get; init; }
|
||||
|
||||
public FileVersion? Cover { get; init; }
|
||||
|
||||
public IReadOnlyList<ContentItem> Items { get; init; } = [];
|
||||
|
||||
public int Order { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Pagination information of a page of data.</summary>
|
||||
public sealed record PageInfo(bool? HasMore, string? Cursor);
|
||||
|
||||
/// <summary>What the reader made of a response.</summary>
|
||||
public enum ReadShape
|
||||
{
|
||||
/// <summary>At least one content, profile or highlight was recognized.</summary>
|
||||
Recognized,
|
||||
|
||||
/// <summary>Nothing to read (empty lists, a bare status): not an error, but counts as an empty page.</summary>
|
||||
Empty,
|
||||
|
||||
/// <summary>A shape the vocabulary does not describe: event «formato non riconosciuto» (spec §6.4).</summary>
|
||||
Unrecognized,
|
||||
}
|
||||
|
||||
/// <summary>Everything one response gave, detached from the JSON document (which is disposed right after).</summary>
|
||||
public sealed record ReadResult
|
||||
{
|
||||
public static ReadResult EmptyResult { get; } = new() { Shape = ReadShape.Empty };
|
||||
|
||||
public required ReadShape Shape { get; init; }
|
||||
|
||||
public IReadOnlyList<ContentItem> Contents { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<ProfileInfo> Profiles { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<HighlightInfo> Highlights { get; init; } = [];
|
||||
|
||||
public PageInfo? Page { get; init; }
|
||||
|
||||
public ProfileInfo? Viewer { get; init; }
|
||||
|
||||
/// <summary>For unrecognized responses: the key structure, without any value (spec §6.4).</summary>
|
||||
public string? KeyStructure { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Febe.Core.Collection.Readers;
|
||||
|
||||
/// <summary>
|
||||
/// One concept of the vocabulary: the keys (or dotted paths, e.g. «image_versions2.candidates») under which a site
|
||||
/// puts a piece of data. Empty means «not known yet».
|
||||
/// </summary>
|
||||
public sealed record VocabularyKeys(IReadOnlyList<string> Paths)
|
||||
{
|
||||
public static VocabularyKeys None { get; } = new([]);
|
||||
|
||||
public bool IsSet => Paths.Count > 0;
|
||||
|
||||
/// <summary>Each path split into its segments.</summary>
|
||||
internal IReadOnlyList<string[]> Segments { get; } = [.. Paths.Select(p => p.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))];
|
||||
|
||||
/// <summary>Looks the concept up in <paramref name="node"/>: the first path that exists wins.</summary>
|
||||
public bool TryGet(JsonElement node, out JsonElement value)
|
||||
{
|
||||
if (node.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (var segments in Segments)
|
||||
{
|
||||
var current = node;
|
||||
var found = true;
|
||||
foreach (var segment in segments)
|
||||
{
|
||||
if (current.ValueKind != JsonValueKind.Object || !current.TryGetProperty(segment, out current))
|
||||
{
|
||||
found = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (found && current.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined))
|
||||
{
|
||||
value = current;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>True when the first segment of one of the paths is a property of <paramref name="node"/>.</summary>
|
||||
public bool Has(JsonElement node) => TryGet(node, out _);
|
||||
|
||||
public override string ToString() => Paths.Count == 0 ? "(non impostato)" : string.Join(" | ", Paths);
|
||||
}
|
||||
|
||||
/// <summary>Keys of a content node: a post, a story, an item of a highlight collection, or a file of a series.</summary>
|
||||
public sealed record ContentKeys
|
||||
{
|
||||
public VocabularyKeys Id { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Code { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>Publication time: a number (Unix seconds, or milliseconds when very large) or an ISO 8601 text.</summary>
|
||||
public VocabularyKeys TakenAt { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Caption { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The image versions: an array of version objects (or a single one).</summary>
|
||||
public VocabularyKeys Images { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The video versions: an array of version objects (or a single one).</summary>
|
||||
public VocabularyKeys Videos { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The files of a series, in order: each one is a content node without its own date.</summary>
|
||||
public VocabularyKeys Children { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>How many files the series declares: when more than the children received, the data is incomplete.</summary>
|
||||
public VocabularyKeys ChildCount { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The author: a profile node.</summary>
|
||||
public VocabularyKeys Owner { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>True for content pinned on top of a profile (not «already known» for the stop rule).</summary>
|
||||
public VocabularyKeys Pinned { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>When a story stops being available (a date, as for <see cref="TakenAt"/>).</summary>
|
||||
public VocabularyKeys ExpiresAt { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>Video duration in seconds (on the node or on the video version).</summary>
|
||||
public VocabularyKeys Duration { get; init; } = VocabularyKeys.None;
|
||||
}
|
||||
|
||||
/// <summary>Keys of one version of a file (one size of an image, one rendition of a video).</summary>
|
||||
public sealed record VersionKeys
|
||||
{
|
||||
public VocabularyKeys Url { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Width { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Height { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>For videos: true when the rendition carries audio and video together (spec §6.5 point 1).</summary>
|
||||
public VocabularyKeys HasAudio { get; init; } = VocabularyKeys.None;
|
||||
}
|
||||
|
||||
/// <summary>Keys of a profile node.</summary>
|
||||
public sealed record ProfileKeys
|
||||
{
|
||||
public VocabularyKeys Id { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Username { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys DisplayName { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys IsPrivate { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>True when Alberto follows the profile.</summary>
|
||||
public VocabularyKeys IsFollowed { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys PostCount { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>Profile picture: a version object, an array of versions or an address.</summary>
|
||||
public VocabularyKeys Picture { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>When the latest active story was published (stories bar, H2).</summary>
|
||||
public VocabularyKeys LatestStoryAt { get; init; } = VocabularyKeys.None;
|
||||
}
|
||||
|
||||
/// <summary>Keys of a highlight collection node.</summary>
|
||||
public sealed record HighlightKeys
|
||||
{
|
||||
public VocabularyKeys Id { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Title { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Owner { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The contents of the collection, when the response carries them.</summary>
|
||||
public VocabularyKeys Items { get; init; } = VocabularyKeys.None;
|
||||
}
|
||||
|
||||
/// <summary>Keys of the pagination information that comes with a page of data.</summary>
|
||||
public sealed record PageKeys
|
||||
{
|
||||
public VocabularyKeys HasMore { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>Opaque resume point given by the site (the backfill stores it).</summary>
|
||||
public VocabularyKeys Cursor { get; init; } = VocabularyKeys.None;
|
||||
}
|
||||
|
||||
/// <summary>Whether the vocabulary is confirmed on real samples or still a hypothesis (spec §6.4, rule 10).</summary>
|
||||
public enum VocabularyStatus
|
||||
{
|
||||
Confirmed,
|
||||
|
||||
/// <summary>Hints only, to be confirmed with the M0 samples: recipes refuse to use it.</summary>
|
||||
Hypothesis,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The key vocabulary of one site (<c>lettori.instagram.json</c>, <c>lettori.prova.json</c>): which keys mean what.
|
||||
/// The reader finds data by shape, wherever it is in the response; the vocabulary only names the keys, so it can be
|
||||
/// updated without recompiling when the site changes (spec §6.4).
|
||||
/// </summary>
|
||||
public sealed record ReaderVocabulary
|
||||
{
|
||||
public required string Site { get; init; }
|
||||
|
||||
public VocabularyStatus Status { get; init; } = VocabularyStatus.Hypothesis;
|
||||
|
||||
public string? Note { get; init; }
|
||||
|
||||
/// <summary>Where it was loaded from, for messages.</summary>
|
||||
public string? Source { get; init; }
|
||||
|
||||
public ContentKeys Content { get; init; } = new();
|
||||
|
||||
public VersionKeys Version { get; init; } = new();
|
||||
|
||||
public ProfileKeys Profile { get; init; } = new();
|
||||
|
||||
public HighlightKeys Highlight { get; init; } = new();
|
||||
|
||||
public PageKeys Page { get; init; } = new();
|
||||
|
||||
/// <summary>The key under which the response describes the connected account (H10).</summary>
|
||||
public VocabularyKeys Viewer { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>
|
||||
/// Concepts the collection pipeline cannot work without, still unset. While this is not empty, or the status is
|
||||
/// a hypothesis, recipes refuse to run on the site.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> MissingConcepts
|
||||
{
|
||||
get
|
||||
{
|
||||
var missing = new List<string>();
|
||||
void Need(VocabularyKeys keys, string name)
|
||||
{
|
||||
if (!keys.IsSet)
|
||||
{
|
||||
missing.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
Need(Content.Id, "content.id");
|
||||
Need(Content.TakenAt, "content.takenAt");
|
||||
Need(Content.Images, "content.images");
|
||||
Need(Content.Videos, "content.videos");
|
||||
Need(Version.Url, "version.url");
|
||||
Need(Version.Width, "version.width");
|
||||
Need(Version.Height, "version.height");
|
||||
Need(Profile.Id, "profile.id");
|
||||
Need(Profile.Username, "profile.username");
|
||||
return missing;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when recipes may rely on this vocabulary.</summary>
|
||||
public bool IsUsable => Status == VocabularyStatus.Confirmed && MissingConcepts.Count == 0;
|
||||
|
||||
/// <summary>Italian explanation of why the vocabulary cannot be used yet, or null.</summary>
|
||||
public string? UnusableReason => IsUsable
|
||||
? null
|
||||
: Status == VocabularyStatus.Hypothesis
|
||||
? $"Il vocabolario dei lettori per «{Site}» è ancora un'ipotesi, da confermare con i campioni di M0 (specifica §6.4, regola 10)."
|
||||
: $"Il vocabolario dei lettori per «{Site}» è incompleto: mancano {string.Join(", ", MissingConcepts)}.";
|
||||
|
||||
/// <summary>The shipped Instagram vocabulary (embedded <c>lettori.instagram.json</c>): hints only.</summary>
|
||||
public static ReaderVocabulary LoadInstagram() => LoadEmbedded("lettori.instagram.json");
|
||||
|
||||
/// <summary>The vocabulary of the local test site (embedded <c>lettori.prova.json</c>).</summary>
|
||||
public static ReaderVocabulary LoadTestSite() => LoadEmbedded("lettori.prova.json");
|
||||
|
||||
/// <summary>Loads <paramref name="path"/> when it exists, otherwise the embedded file with the same name.</summary>
|
||||
public static ReaderVocabulary LoadOrEmbedded(string? path, string embeddedName) =>
|
||||
!string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadEmbedded(embeddedName);
|
||||
|
||||
public static ReaderVocabulary Load(string path) => Parse(File.ReadAllText(path), path);
|
||||
|
||||
public static ReaderVocabulary LoadEmbedded(string fileName)
|
||||
{
|
||||
var resource = $"Febe.Core.Config.{fileName}";
|
||||
using var stream = typeof(ReaderVocabulary).Assembly.GetManifestResourceStream(resource)
|
||||
?? throw new FileNotFoundException($"Risorsa incorporata mancante: {resource}");
|
||||
using var reader = new StreamReader(stream);
|
||||
return Parse(reader.ReadToEnd(), fileName);
|
||||
}
|
||||
|
||||
public static ReaderVocabulary Parse(string json, string? source = null)
|
||||
{
|
||||
var name = source ?? "lettori";
|
||||
VocabularyFile? file;
|
||||
try
|
||||
{
|
||||
file = JsonSerializer.Deserialize(json, VocabularyJsonContext.Default.VocabularyFile);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{name}: file non valido (riga {ex.LineNumber + 1}): {ex.Message.Split('.')[0]}.", ex);
|
||||
}
|
||||
|
||||
if (file is null || string.IsNullOrWhiteSpace(file.Site))
|
||||
{
|
||||
throw new InvalidDataException($"{name}: manca «site».");
|
||||
}
|
||||
|
||||
var status = file.Status?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"confermato" or "confirmed" => VocabularyStatus.Confirmed,
|
||||
"ipotesi" or "hypothesis" or null or "" => VocabularyStatus.Hypothesis,
|
||||
_ => throw new InvalidDataException($"{name}: stato «{file.Status}» sconosciuto (ammessi: confermato, ipotesi)."),
|
||||
};
|
||||
|
||||
static VocabularyKeys K(List<string>? paths) =>
|
||||
paths is null ? VocabularyKeys.None : new VocabularyKeys([.. paths.Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p.Trim())]);
|
||||
|
||||
var c = file.Content ?? new ContentDto();
|
||||
var v = file.Version ?? new VersionDto();
|
||||
var p = file.Profile ?? new ProfileDto();
|
||||
var h = file.Highlight ?? new HighlightDto();
|
||||
var g = file.Page ?? new PageDto();
|
||||
return new ReaderVocabulary
|
||||
{
|
||||
Site = file.Site.Trim(),
|
||||
Status = status,
|
||||
Note = file.Note,
|
||||
Source = source,
|
||||
Content = new ContentKeys
|
||||
{
|
||||
Id = K(c.Id),
|
||||
Code = K(c.Code),
|
||||
TakenAt = K(c.TakenAt),
|
||||
Caption = K(c.Caption),
|
||||
Images = K(c.Images),
|
||||
Videos = K(c.Videos),
|
||||
Children = K(c.Children),
|
||||
ChildCount = K(c.ChildCount),
|
||||
Owner = K(c.Owner),
|
||||
Pinned = K(c.Pinned),
|
||||
ExpiresAt = K(c.ExpiresAt),
|
||||
Duration = K(c.Duration),
|
||||
},
|
||||
Version = new VersionKeys { Url = K(v.Url), Width = K(v.Width), Height = K(v.Height), HasAudio = K(v.HasAudio) },
|
||||
Profile = new ProfileKeys
|
||||
{
|
||||
Id = K(p.Id),
|
||||
Username = K(p.Username),
|
||||
DisplayName = K(p.DisplayName),
|
||||
IsPrivate = K(p.IsPrivate),
|
||||
IsFollowed = K(p.IsFollowed),
|
||||
PostCount = K(p.PostCount),
|
||||
Picture = K(p.Picture),
|
||||
LatestStoryAt = K(p.LatestStoryAt),
|
||||
},
|
||||
Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items) },
|
||||
Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) },
|
||||
Viewer = K(file.Viewer),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class VocabularyFile
|
||||
{
|
||||
public string? Site { get; set; }
|
||||
|
||||
public string? Status { get; set; }
|
||||
|
||||
public string? Note { get; set; }
|
||||
|
||||
public ContentDto? Content { get; set; }
|
||||
|
||||
public VersionDto? Version { get; set; }
|
||||
|
||||
public ProfileDto? Profile { get; set; }
|
||||
|
||||
public HighlightDto? Highlight { get; set; }
|
||||
|
||||
public PageDto? Page { get; set; }
|
||||
|
||||
public List<string>? Viewer { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class ContentDto
|
||||
{
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<string>? Id { get; set; }
|
||||
|
||||
public List<string>? Code { get; set; }
|
||||
|
||||
public List<string>? TakenAt { get; set; }
|
||||
|
||||
public List<string>? Caption { get; set; }
|
||||
|
||||
public List<string>? Images { get; set; }
|
||||
|
||||
public List<string>? Videos { get; set; }
|
||||
|
||||
public List<string>? Children { get; set; }
|
||||
|
||||
public List<string>? ChildCount { get; set; }
|
||||
|
||||
public List<string>? Owner { get; set; }
|
||||
|
||||
public List<string>? Pinned { get; set; }
|
||||
|
||||
public List<string>? ExpiresAt { get; set; }
|
||||
|
||||
public List<string>? Duration { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class VersionDto
|
||||
{
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<string>? Url { get; set; }
|
||||
|
||||
public List<string>? Width { get; set; }
|
||||
|
||||
public List<string>? Height { get; set; }
|
||||
|
||||
public List<string>? HasAudio { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class ProfileDto
|
||||
{
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<string>? Id { get; set; }
|
||||
|
||||
public List<string>? Username { get; set; }
|
||||
|
||||
public List<string>? DisplayName { get; set; }
|
||||
|
||||
public List<string>? IsPrivate { get; set; }
|
||||
|
||||
public List<string>? IsFollowed { get; set; }
|
||||
|
||||
public List<string>? PostCount { get; set; }
|
||||
|
||||
public List<string>? Picture { get; set; }
|
||||
|
||||
public List<string>? LatestStoryAt { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class HighlightDto
|
||||
{
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<string>? Id { get; set; }
|
||||
|
||||
public List<string>? Title { get; set; }
|
||||
|
||||
public List<string>? Owner { get; set; }
|
||||
|
||||
public List<string>? Items { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class PageDto
|
||||
{
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<string>? HasMore { get; set; }
|
||||
|
||||
public List<string>? Cursor { get; set; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
AllowTrailingCommas = true,
|
||||
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow)]
|
||||
[JsonSerializable(typeof(VocabularyFile))]
|
||||
internal sealed partial class VocabularyJsonContext : JsonSerializerContext;
|
||||
@@ -0,0 +1,488 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Collection.Readers;
|
||||
|
||||
/// <summary>
|
||||
/// The generic reader (spec §6.4): walks any JSON tree and recognizes, wherever they are, the nodes that look like a
|
||||
/// content (identifier, date, image or video versions, possibly a series), a profile (identifier and user name), a
|
||||
/// highlight collection (identifier and title) and the pagination of a page. Which keys mean what comes from the
|
||||
/// site's <see cref="ReaderVocabulary"/>, never from fixed paths or addresses.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Version choice (spec §6.5 point 1): the largest image; for videos the largest among the versions complete with
|
||||
/// audio (versions that do not say are taken as complete), or the largest of all when none has audio.
|
||||
/// Thread-safe: the reader keeps no state between calls.
|
||||
/// </remarks>
|
||||
public sealed class ShapeReader
|
||||
{
|
||||
private const int MaxDepth = 64;
|
||||
|
||||
private readonly ReaderVocabulary _v;
|
||||
|
||||
public ShapeReader(ReaderVocabulary vocabulary)
|
||||
{
|
||||
_v = vocabulary ?? throw new ArgumentNullException(nameof(vocabulary));
|
||||
}
|
||||
|
||||
public ReaderVocabulary Vocabulary => _v;
|
||||
|
||||
/// <summary>Reads one response body. Never throws on unexpected shapes: they become <see cref="ReadShape.Unrecognized"/>.</summary>
|
||||
public ReadResult Read(JsonElement root)
|
||||
{
|
||||
var walk = new Walk();
|
||||
Visit(root, walk, owner: null, highlightId: null, depth: 0);
|
||||
|
||||
var profiles = walk.Profiles.Values.ToList();
|
||||
var viewer = profiles.FirstOrDefault(p => p.IsViewer);
|
||||
if (walk.Contents.Count > 0 || walk.Highlights.Count > 0 || profiles.Count > 0)
|
||||
{
|
||||
return new ReadResult
|
||||
{
|
||||
Shape = ReadShape.Recognized,
|
||||
Contents = walk.Contents,
|
||||
Profiles = profiles,
|
||||
Highlights = walk.Highlights,
|
||||
Page = walk.Page,
|
||||
Viewer = viewer,
|
||||
};
|
||||
}
|
||||
|
||||
if (IsEmptyShape(root, walk.Page is not null))
|
||||
{
|
||||
return new ReadResult { Shape = ReadShape.Empty, Page = walk.Page };
|
||||
}
|
||||
|
||||
return new ReadResult { Shape = ReadShape.Unrecognized, Page = walk.Page, KeyStructure = KeyStructure.Describe(root) };
|
||||
}
|
||||
|
||||
/// <summary>Reads a body given as text (tests, probe samples).</summary>
|
||||
public ReadResult Read(string json)
|
||||
{
|
||||
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 256 });
|
||||
return Read(document.RootElement);
|
||||
}
|
||||
|
||||
private void Visit(JsonElement node, Walk walk, ProfileInfo? owner, string? highlightId, int depth)
|
||||
{
|
||||
if (depth > MaxDepth)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (node.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var item in node.EnumerateArray())
|
||||
{
|
||||
Visit(item, walk, owner, highlightId, depth + 1);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (node.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (walk.Page is null && (_v.Page.HasMore.Has(node) || _v.Page.Cursor.Has(node)))
|
||||
{
|
||||
walk.Page = new PageInfo(
|
||||
_v.Page.HasMore.TryGet(node, out var more) ? AsBool(more) : null,
|
||||
_v.Page.Cursor.TryGet(node, out var cursor) ? AsText(cursor) : null);
|
||||
}
|
||||
|
||||
if (_v.Viewer.TryGet(node, out var viewerNode) && ReadProfile(viewerNode) is { } viewer)
|
||||
{
|
||||
walk.AddProfile(viewer with { IsViewer = true });
|
||||
}
|
||||
|
||||
if (IsContent(node))
|
||||
{
|
||||
if (ReadContent(node, walk, owner, highlightId) is { } item)
|
||||
{
|
||||
walk.Contents.Add(item);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsHighlight(node))
|
||||
{
|
||||
var highlightOwner = _v.Highlight.Owner.TryGet(node, out var ho) ? ReadProfile(ho) ?? owner : owner;
|
||||
if (highlightOwner is not null)
|
||||
{
|
||||
walk.AddProfile(highlightOwner);
|
||||
}
|
||||
|
||||
var id = AsText(Get(_v.Highlight.Id, node))!;
|
||||
var before = walk.Contents.Count;
|
||||
if (_v.Highlight.Items.TryGet(node, out var items))
|
||||
{
|
||||
Visit(items, walk, highlightOwner, id, depth + 1);
|
||||
}
|
||||
|
||||
walk.Highlights.Add(new HighlightInfo
|
||||
{
|
||||
Id = id,
|
||||
Title = AsText(Get(_v.Highlight.Title, node)) ?? string.Empty,
|
||||
Owner = highlightOwner,
|
||||
Items = walk.Contents.Skip(before).ToList(),
|
||||
Order = walk.Highlights.Count,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var inherited = owner;
|
||||
if (ReadProfile(node) is { } profile)
|
||||
{
|
||||
walk.AddProfile(profile);
|
||||
inherited = profile;
|
||||
}
|
||||
else if (_v.Content.Owner.TryGet(node, out var ownerNode) && ReadProfile(ownerNode) is { } declared)
|
||||
{
|
||||
// An object that declares an author for what it contains (e.g. the stories of one account).
|
||||
walk.AddProfile(declared);
|
||||
inherited = declared;
|
||||
}
|
||||
|
||||
foreach (var property in node.EnumerateObject())
|
||||
{
|
||||
if (property.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
|
||||
{
|
||||
Visit(property.Value, walk, inherited, highlightId, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsContent(JsonElement node) =>
|
||||
_v.Content.Id.Has(node) && _v.Content.TakenAt.Has(node)
|
||||
&& (_v.Content.Images.Has(node) || _v.Content.Videos.Has(node) || _v.Content.Children.Has(node));
|
||||
|
||||
private bool IsHighlight(JsonElement node) =>
|
||||
_v.Highlight.Id.Has(node) && _v.Highlight.Title.Has(node) && AsText(Get(_v.Highlight.Id, node)) is not null;
|
||||
|
||||
private ContentItem? ReadContent(JsonElement node, Walk walk, ProfileInfo? inheritedOwner, string? highlightId)
|
||||
{
|
||||
var id = AsText(Get(_v.Content.Id, node));
|
||||
var takenAt = AsTime(Get(_v.Content.TakenAt, node));
|
||||
if (id is null || takenAt is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var owner = _v.Content.Owner.TryGet(node, out var ownerNode) ? ReadProfile(ownerNode) ?? inheritedOwner : inheritedOwner;
|
||||
if (owner is not null)
|
||||
{
|
||||
walk.AddProfile(owner);
|
||||
}
|
||||
|
||||
var files = new List<ContentFile>();
|
||||
var hasChildren = _v.Content.Children.TryGet(node, out var children) && children.ValueKind == JsonValueKind.Array && children.GetArrayLength() > 0;
|
||||
var declaredChildren = 0;
|
||||
if (hasChildren)
|
||||
{
|
||||
foreach (var child in children.EnumerateArray())
|
||||
{
|
||||
declaredChildren++;
|
||||
if (child.ValueKind == JsonValueKind.Object && ReadFile(child) is { } file)
|
||||
{
|
||||
files.Add(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (ReadFile(node) is { } single)
|
||||
{
|
||||
files.Add(single);
|
||||
}
|
||||
|
||||
var complete = files.Count > 0 && (!hasChildren || files.Count == declaredChildren);
|
||||
if (_v.Content.ChildCount.TryGet(node, out var countNode) && AsInt(countNode) is { } declared && declared > files.Count)
|
||||
{
|
||||
complete = false;
|
||||
}
|
||||
|
||||
return new ContentItem
|
||||
{
|
||||
Id = id,
|
||||
Code = AsText(Get(_v.Content.Code, node)),
|
||||
TakenAt = takenAt.Value,
|
||||
Caption = AsText(Get(_v.Content.Caption, node)),
|
||||
Owner = owner,
|
||||
Pinned = _v.Content.Pinned.TryGet(node, out var pinned) && AsBool(pinned) == true,
|
||||
ExpiresAt = AsTime(Get(_v.Content.ExpiresAt, node)),
|
||||
Files = files,
|
||||
IsComplete = complete,
|
||||
HighlightId = highlightId,
|
||||
Order = walk.Contents.Count,
|
||||
};
|
||||
}
|
||||
|
||||
private ContentFile? ReadFile(JsonElement node)
|
||||
{
|
||||
var videos = _v.Content.Videos.TryGet(node, out var v) ? ReadVersions(v) : [];
|
||||
var images = _v.Content.Images.TryGet(node, out var i) ? ReadVersions(i) : [];
|
||||
var id = AsText(Get(_v.Content.Id, node));
|
||||
var largestImage = images.Count == 0 ? null : images.MaxBy(x => x.Version.Area);
|
||||
if (videos.Count > 0)
|
||||
{
|
||||
var complete = videos.Where(x => x.Version.HasAudio != false).ToList();
|
||||
var best = (complete.Count > 0 ? complete : videos).MaxBy(x => x.Version.Area)!;
|
||||
var duration = AsSeconds(Get(_v.Content.Duration, node)) ?? AsSeconds(Get(_v.Content.Duration, best.Node));
|
||||
return new ContentFile(MediaKind.Video, id, best.Version, largestImage?.Version, duration);
|
||||
}
|
||||
|
||||
return largestImage is null ? null : new ContentFile(MediaKind.Photo, id, largestImage.Version, null, null);
|
||||
}
|
||||
|
||||
private List<VersionNode> ReadVersions(JsonElement value)
|
||||
{
|
||||
var list = new List<VersionNode>();
|
||||
switch (value.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in value.EnumerateArray())
|
||||
{
|
||||
if (ReadVersion(item) is { } version)
|
||||
{
|
||||
list.Add(new VersionNode(version, item));
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.Object:
|
||||
case JsonValueKind.String:
|
||||
if (ReadVersion(value) is { } single)
|
||||
{
|
||||
list.Add(new VersionNode(single, value));
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private FileVersion? ReadVersion(JsonElement node)
|
||||
{
|
||||
if (node.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
return IsAddress(node.GetString()) ? new FileVersion(node.GetString()!, null, null, null) : null;
|
||||
}
|
||||
|
||||
if (node.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var url = AsText(Get(_v.Version.Url, node));
|
||||
if (!IsAddress(url))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new FileVersion(
|
||||
url!,
|
||||
AsInt(Get(_v.Version.Width, node)),
|
||||
AsInt(Get(_v.Version.Height, node)),
|
||||
_v.Version.HasAudio.TryGet(node, out var audio) ? AsBool(audio) : null);
|
||||
}
|
||||
|
||||
private ProfileInfo? ReadProfile(JsonElement node)
|
||||
{
|
||||
if (node.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var id = AsText(Get(_v.Profile.Id, node));
|
||||
var username = AsText(Get(_v.Profile.Username, node));
|
||||
if (id is null || string.IsNullOrWhiteSpace(username))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
FileVersion? picture = null;
|
||||
if (_v.Profile.Picture.TryGet(node, out var pictureNode))
|
||||
{
|
||||
picture = ReadVersions(pictureNode).MaxBy(x => x.Version.Area)?.Version;
|
||||
}
|
||||
|
||||
return new ProfileInfo
|
||||
{
|
||||
Id = id,
|
||||
Username = username.Trim(),
|
||||
DisplayName = AsText(Get(_v.Profile.DisplayName, node)),
|
||||
IsPrivate = _v.Profile.IsPrivate.TryGet(node, out var p) ? AsBool(p) : null,
|
||||
IsFollowed = _v.Profile.IsFollowed.TryGet(node, out var f) ? AsBool(f) : null,
|
||||
PostCount = AsInt(Get(_v.Profile.PostCount, node)),
|
||||
Picture = picture,
|
||||
LatestStoryAt = AsTime(Get(_v.Profile.LatestStoryAt, node)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Empty»: no list with elements anywhere, and either a recognized pagination or only plain values at the top
|
||||
/// (a bare status or error). Anything richer that nothing recognized is an unknown shape.
|
||||
/// </summary>
|
||||
private static bool IsEmptyShape(JsonElement root, bool hasPage)
|
||||
{
|
||||
var nested = false;
|
||||
var nonEmptyArray = false;
|
||||
Scan(root, 0, ref nested, ref nonEmptyArray);
|
||||
return !nonEmptyArray && (hasPage || !nested);
|
||||
}
|
||||
|
||||
private static void Scan(JsonElement element, int depth, ref bool nested, ref bool nonEmptyArray)
|
||||
{
|
||||
if (depth > MaxDepth)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (property.Value.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
nested = true;
|
||||
}
|
||||
|
||||
Scan(property.Value, depth + 1, ref nested, ref nonEmptyArray);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.Array:
|
||||
if (element.GetArrayLength() > 0)
|
||||
{
|
||||
nonEmptyArray = true;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonElement Get(VocabularyKeys keys, JsonElement node) => keys.TryGet(node, out var value) ? value : default;
|
||||
|
||||
private static bool IsAddress(string? text) =>
|
||||
!string.IsNullOrWhiteSpace(text)
|
||||
&& Uri.TryCreate(text, UriKind.Absolute, out var uri)
|
||||
&& uri.Scheme is "http" or "https";
|
||||
|
||||
internal static string? AsText(JsonElement value) => value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => string.IsNullOrEmpty(value.GetString()) ? null : value.GetString(),
|
||||
JsonValueKind.Number => value.GetRawText(),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
internal static int? AsInt(JsonElement value)
|
||||
{
|
||||
switch (value.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Number when value.TryGetInt32(out var i):
|
||||
return i;
|
||||
case JsonValueKind.Number when value.TryGetDouble(out var d) && d is >= int.MinValue and <= int.MaxValue:
|
||||
return (int)Math.Round(d);
|
||||
case JsonValueKind.String when int.TryParse(value.GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var s):
|
||||
return s;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool? AsBool(JsonElement value) => value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.True => true,
|
||||
JsonValueKind.False => false,
|
||||
JsonValueKind.Number => value.TryGetInt64(out var n) ? n != 0 : null,
|
||||
JsonValueKind.String => value.GetString()?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"true" or "1" or "sì" or "si" => true,
|
||||
"false" or "0" or "no" => false,
|
||||
_ => null,
|
||||
},
|
||||
_ => null,
|
||||
};
|
||||
|
||||
internal static TimeSpan? AsSeconds(JsonElement value)
|
||||
{
|
||||
double? seconds = value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Number when value.TryGetDouble(out var d) => d,
|
||||
JsonValueKind.String when double.TryParse(value.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var s) => s,
|
||||
_ => null,
|
||||
};
|
||||
return seconds is { } x && x >= 0 && x < 1e7 ? TimeSpan.FromSeconds(x) : null;
|
||||
}
|
||||
|
||||
/// <summary>A date: Unix seconds (milliseconds when larger than 10^11), or ISO 8601 text.</summary>
|
||||
internal static DateTimeOffset? AsTime(JsonElement value)
|
||||
{
|
||||
switch (value.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Number when value.TryGetDouble(out var n):
|
||||
return FromUnix(n);
|
||||
case JsonValueKind.String:
|
||||
var text = value.GetString();
|
||||
if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var numeric))
|
||||
{
|
||||
return FromUnix(numeric);
|
||||
}
|
||||
|
||||
return DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var parsed)
|
||||
? parsed
|
||||
: null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static DateTimeOffset? FromUnix(double value)
|
||||
{
|
||||
if (value <= 0 || double.IsNaN(value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var ms = value > 1e11 ? value : value * 1000;
|
||||
return ms < 253402300799000 ? DateTimeOffset.FromUnixTimeMilliseconds((long)ms) : null;
|
||||
}
|
||||
|
||||
private sealed record VersionNode(FileVersion Version, JsonElement Node);
|
||||
|
||||
private sealed class Walk
|
||||
{
|
||||
public List<ContentItem> Contents { get; } = [];
|
||||
|
||||
public List<HighlightInfo> Highlights { get; } = [];
|
||||
|
||||
public Dictionary<string, ProfileInfo> Profiles { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public PageInfo? Page { get; set; }
|
||||
|
||||
/// <summary>Merges what different parts of a response say about the same profile.</summary>
|
||||
public void AddProfile(ProfileInfo profile)
|
||||
{
|
||||
if (!Profiles.TryGetValue(profile.Id, out var known))
|
||||
{
|
||||
Profiles[profile.Id] = profile;
|
||||
return;
|
||||
}
|
||||
|
||||
Profiles[profile.Id] = known with
|
||||
{
|
||||
DisplayName = known.DisplayName ?? profile.DisplayName,
|
||||
IsPrivate = known.IsPrivate ?? profile.IsPrivate,
|
||||
IsFollowed = known.IsFollowed ?? profile.IsFollowed,
|
||||
PostCount = known.PostCount ?? profile.PostCount,
|
||||
Picture = known.Picture ?? profile.Picture,
|
||||
LatestStoryAt = known.LatestStoryAt ?? profile.LatestStoryAt,
|
||||
IsViewer = known.IsViewer || profile.IsViewer,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
/// <summary>One response read by the reader, in arrival order.</summary>
|
||||
/// <param name="Sequence">Arrival number, from 1.</param>
|
||||
/// <param name="Response">Sanitized descriptor (no query string).</param>
|
||||
/// <param name="Result">What the reader recognized, detached from the body.</param>
|
||||
public sealed record CapturedRead(long Sequence, ResponseDescriptor Response, ReadResult Result);
|
||||
|
||||
/// <summary>
|
||||
/// Bridge between the response tap and the recipes (spec §6.2, §6.4): every JSON body the site sends is read by the
|
||||
/// <see cref="ShapeReader"/> as it arrives, and the recipes wait for what they expect after a gesture. Bodies are
|
||||
/// never kept: only the reader's detached results are.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It also tracks which data responses are still on their way (their body not read yet), so a recipe can wait until
|
||||
/// the page has settled. Thread-safe.
|
||||
/// </remarks>
|
||||
public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
{
|
||||
private const int MaxKept = 2000;
|
||||
|
||||
private readonly ShapeReader _reader;
|
||||
private readonly IClock _clock;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<CapturedRead> _reads = [];
|
||||
private readonly Dictionary<string, DateTimeOffset> _pending = new(StringComparer.Ordinal);
|
||||
private long _sequence;
|
||||
|
||||
public CaptureCollector(ShapeReader reader, IClock clock)
|
||||
{
|
||||
_reader = reader ?? throw new ArgumentNullException(nameof(reader));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
}
|
||||
|
||||
public ShapeReader Reader => _reader;
|
||||
|
||||
/// <summary>How long a data response may stay «on its way» before it is forgotten (its body may never come).</summary>
|
||||
public TimeSpan PendingLifetime { get; init; } = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>Sequence number of the last read: pass it to <see cref="Since"/> to get what arrives after now.</summary>
|
||||
public long Mark()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _sequence;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads that arrived after <paramref name="mark"/>, oldest first.</summary>
|
||||
public IReadOnlyList<CapturedRead> Since(long mark)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return [.. _reads.Where(r => r.Sequence > mark)];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Data responses whose body has not been read yet.</summary>
|
||||
public int Pending
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ExpirePending();
|
||||
return _pending.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until the reads after <paramref name="mark"/> satisfy <paramref name="until"/>, or <paramref name="timeout"/>
|
||||
/// passes. Returns the reads after the mark either way.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<CapturedRead>> WaitAsync(long mark, Func<IReadOnlyList<CapturedRead>, bool> until, TimeSpan timeout, TimeSpan poll, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(until);
|
||||
var deadline = _clock.Now + timeout;
|
||||
while (true)
|
||||
{
|
||||
var reads = Since(mark);
|
||||
if (until(reads) || _clock.Now >= deadline)
|
||||
{
|
||||
return reads;
|
||||
}
|
||||
|
||||
await _clock.Delay(poll, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until no data response is on its way and nothing new arrived for <paramref name="quiet"/>, at most
|
||||
/// <paramref name="timeout"/>.
|
||||
/// </summary>
|
||||
public async Task SettleAsync(TimeSpan quiet, TimeSpan timeout, TimeSpan poll, CancellationToken ct)
|
||||
{
|
||||
var deadline = _clock.Now + timeout;
|
||||
var lastSeen = Mark();
|
||||
var quietSince = _clock.Now;
|
||||
while (_clock.Now < deadline)
|
||||
{
|
||||
await _clock.Delay(poll, ct).ConfigureAwait(false);
|
||||
var current = Mark();
|
||||
if (current != lastSeen || Pending > 0)
|
||||
{
|
||||
lastSeen = current;
|
||||
quietSince = _clock.Now;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (_clock.Now - quietSince >= quiet)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forgets everything (start of a recipe).</summary>
|
||||
public void Clear()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_reads.Clear();
|
||||
_pending.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
ValueTask IResponseConsumer.ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
|
||||
{
|
||||
Accept(response, body.RootElement);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Reads one body (also used by tests and the probe samples).</summary>
|
||||
public CapturedRead? Accept(ResponseDescriptor response, JsonElement body)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(response);
|
||||
lock (_gate)
|
||||
{
|
||||
_pending.Remove(response.RequestId);
|
||||
}
|
||||
|
||||
if (response.HostKind != HostKind.Site)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var result = _reader.Read(body);
|
||||
lock (_gate)
|
||||
{
|
||||
var read = new CapturedRead(++_sequence, response, result);
|
||||
_reads.Add(read);
|
||||
if (_reads.Count > MaxKept)
|
||||
{
|
||||
_reads.RemoveRange(0, _reads.Count - MaxKept);
|
||||
}
|
||||
|
||||
return read;
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnResponse(ResponseDescriptor response)
|
||||
{
|
||||
if (response.HostKind == HostKind.Site
|
||||
&& response.MimeType.Contains("json", StringComparison.OrdinalIgnoreCase)
|
||||
&& response.Status is >= 200 and < 600 && response.Status != 204)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_pending[response.RequestId] = _clock.Now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnNavigation(NavigationDescriptor navigation)
|
||||
{
|
||||
if (!navigation.SameDocument)
|
||||
{
|
||||
// Bodies of the previous document will not be read any more (the tap forgets them too).
|
||||
lock (_gate)
|
||||
{
|
||||
_pending.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ExpirePending()
|
||||
{
|
||||
var limit = _clock.Now - PendingLifetime;
|
||||
foreach (var key in _pending.Where(p => p.Value < limit).Select(p => p.Key).ToList())
|
||||
{
|
||||
_pending.Remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
/// <summary>What saving a content item did.</summary>
|
||||
public enum SaveOutcome
|
||||
{
|
||||
/// <summary>A new entry with its files to download.</summary>
|
||||
Created,
|
||||
|
||||
/// <summary>Already known (in any state, deleted included): nothing new.</summary>
|
||||
Known,
|
||||
|
||||
/// <summary>An imported entry recognized by account, kind and time (spec §9.5): it took the Instagram data.</summary>
|
||||
Enriched,
|
||||
|
||||
/// <summary>Not wanted: the account's switches or limits exclude it.</summary>
|
||||
Excluded,
|
||||
}
|
||||
|
||||
/// <summary>Result of <see cref="CollectionWriter.SaveAsync"/>.</summary>
|
||||
public sealed record SaveResult(SaveOutcome Outcome, Entry? Entry);
|
||||
|
||||
/// <summary>
|
||||
/// Turns what the readers recognized into stored records: entries and files (with the account's switches and limits),
|
||||
/// imported entries recognized after the fact (spec §9.5), renamed accounts (spec §4.2), highlight collections and
|
||||
/// their contents (H9), tasks for «Post singolo», and the readable events of the timeline. Never logs captions or
|
||||
/// addresses.
|
||||
/// </summary>
|
||||
public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
{
|
||||
/// <summary>Tolerance for recognizing imported entries by publication time (spec §9.5: two seconds).</summary>
|
||||
public static readonly TimeSpan ImportedTimeTolerance = TimeSpan.FromSeconds(2);
|
||||
|
||||
public IFebeStorage Storage => storage;
|
||||
|
||||
/// <summary>
|
||||
/// A profile seen in the data. The account is identified by its numeric id; when its name changed, a followed
|
||||
/// profile is renamed (folder kept, notice raised) and a profile that is not followed becomes «Non raggiungibile»
|
||||
/// until Alberto confirms the new name (spec §4.2). Returns the account, or null when Febe does not track it.
|
||||
/// </summary>
|
||||
public async Task<Account?> ObserveProfileAsync(ProfileInfo profile, long? sessionId, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
var account = await storage.Accounts.FindByInstagramIdAsync(profile.Id, ct).ConfigureAwait(false);
|
||||
if (account is null || string.Equals(account.Username, profile.Username, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return account;
|
||||
}
|
||||
|
||||
var now = clock.Now;
|
||||
if (account.IsFollowed || profile.IsFollowed == true || account.IsMine)
|
||||
{
|
||||
var old = account.Username;
|
||||
await storage.Accounts.RenameAsync(account.Id, profile.Username, now, ct).ConfigureAwait(false);
|
||||
await EventAsync("account-rinominato", $"{old} ora si chiama {profile.Username}: nome aggiornato, la cartella resta la stessa.", EventSeverity.Warning, account.Id, sessionId, ct).ConfigureAwait(false);
|
||||
}
|
||||
else if (account.State != AccountState.Unreachable)
|
||||
{
|
||||
await storage.Accounts.SetStateAsync(account.Id, AccountState.Unreachable, now, UnreachableReason.Renamed, ct).ConfigureAwait(false);
|
||||
await EventAsync("account-non-raggiungibile", $"{account.Username} ha cambiato nome e non è un profilo seguito: indica il nuovo nome per riprendere.", EventSeverity.Warning, account.Id, sessionId, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await storage.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the facts of a profile read during a check: identifier (first time), privacy, follow state, number of
|
||||
/// posts, display name, time of the check. Returns the updated account.
|
||||
/// </summary>
|
||||
public async Task<Account> ApplyProfileAsync(Account account, ProfileInfo profile, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
if (account.InstagramId is null)
|
||||
{
|
||||
await storage.Accounts.UpdateAsync(account with { InstagramId = profile.Id }, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await storage.Accounts.UpdateChecksAsync(
|
||||
account.Id,
|
||||
new AccountCheckTimes
|
||||
{
|
||||
LastProfileCheckAt = clock.Now,
|
||||
PostCount = profile.PostCount,
|
||||
IsPrivate = profile.IsPrivate,
|
||||
IsFollowed = profile.IsFollowed,
|
||||
DisplayName = profile.DisplayName,
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
return await storage.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account;
|
||||
}
|
||||
|
||||
/// <summary>Whether the account wants entries of this kind («Cosa scaricare», spec §4.4).</summary>
|
||||
public static bool Wants(Account account, EntryKind kind)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
return kind switch
|
||||
{
|
||||
EntryKind.Post => (account.ContentTypes & (ContentTypes.PostPhotos | ContentTypes.PostVideos)) != 0,
|
||||
EntryKind.Story => account.ContentTypes.HasFlag(ContentTypes.Stories),
|
||||
EntryKind.Highlight => account.ContentTypes.HasFlag(ContentTypes.Highlights),
|
||||
EntryKind.Tagged => account.ContentTypes.HasFlag(ContentTypes.Tagged),
|
||||
EntryKind.ProfilePicture => account.ContentTypes.HasFlag(ContentTypes.ProfilePicture),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Why a file is skipped by the account's settings, or null when it is wanted.</summary>
|
||||
public static string? SkipReason(Account account, EntryKind kind, MediaKind media)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
return (kind, media) switch
|
||||
{
|
||||
(EntryKind.Story, MediaKind.Video) when !account.Limits.StoryVideos => "Video delle storie esclusi nelle impostazioni dell'account.",
|
||||
(EntryKind.Post, MediaKind.Video) when !account.ContentTypes.HasFlag(ContentTypes.PostVideos) => "«Video e reel» è spento per questo account.",
|
||||
(EntryKind.Post, MediaKind.Photo) when !account.ContentTypes.HasFlag(ContentTypes.PostPhotos) => "«Foto dei post» è spento per questo account.",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves a content item as an entry of <paramref name="kind"/> for <paramref name="account"/>, unless it is known,
|
||||
/// excluded by the account's settings, or an imported entry recognized by time (§9.5). An incomplete series is
|
||||
/// saved with the files received and a «Post singolo» task is queued to complete it.
|
||||
/// </summary>
|
||||
public async Task<SaveResult> SaveAsync(Account account, ContentItem item, EntryKind kind, long? sessionId, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
if (!Wants(account, kind))
|
||||
{
|
||||
return new SaveResult(SaveOutcome.Excluded, null);
|
||||
}
|
||||
|
||||
var known = await storage.Entries.FindAsync(account.Id, kind, item.Id, ct).ConfigureAwait(false);
|
||||
if (known is not null)
|
||||
{
|
||||
await RefreshExpiredAsync(known, item, ct).ConfigureAwait(false);
|
||||
return new SaveResult(SaveOutcome.Known, known);
|
||||
}
|
||||
|
||||
if (kind is EntryKind.Post or EntryKind.Tagged
|
||||
&& account.Limits.Depth == HistoryDepth.FromDate && account.Limits.FromDate is { } from && item.TakenAt < from)
|
||||
{
|
||||
return new SaveResult(SaveOutcome.Excluded, null);
|
||||
}
|
||||
|
||||
if (kind != EntryKind.ProfilePicture
|
||||
&& await storage.Entries.FindByPublicationTimeAsync(account.Id, kind, item.TakenAt, ImportedTimeTolerance, ct).ConfigureAwait(false) is { InstagramId: null } imported)
|
||||
{
|
||||
var enriched = imported with
|
||||
{
|
||||
InstagramId = item.Id,
|
||||
Code = imported.Code ?? item.Code,
|
||||
Caption = imported.Caption ?? item.Caption,
|
||||
};
|
||||
await storage.Entries.UpdateAsync(enriched, ct).ConfigureAwait(false);
|
||||
return new SaveResult(SaveOutcome.Enriched, enriched);
|
||||
}
|
||||
|
||||
var now = clock.Now;
|
||||
var entry = ReadMapping.ToEntry(item, account.Id, kind, now);
|
||||
var media = ReadMapping.ToMedia(item, now).Select(m => ApplyPolicy(account, kind, m)).ToList();
|
||||
var added = await storage.Entries.AddAsync(entry, media, ct).ConfigureAwait(false);
|
||||
if (!added.Created)
|
||||
{
|
||||
return new SaveResult(SaveOutcome.Known, added.Stored.Entry);
|
||||
}
|
||||
|
||||
if (!item.IsComplete && kind is EntryKind.Post or EntryKind.Tagged)
|
||||
{
|
||||
await QueueSinglePostAsync(added.Stored.Entry, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new SaveResult(SaveOutcome.Created, added.Stored.Entry);
|
||||
}
|
||||
|
||||
/// <summary>Saves the profile picture when its address identity is new (code = first eight hex digits of SHA-256).</summary>
|
||||
public async Task<SaveResult> SaveProfilePictureAsync(Account account, ProfileInfo profile, CancellationToken ct)
|
||||
{
|
||||
if (!Wants(account, EntryKind.ProfilePicture) || ReadMapping.ToProfilePicture(profile, account.Id, clock.Now) is not { } picture)
|
||||
{
|
||||
return new SaveResult(SaveOutcome.Excluded, null);
|
||||
}
|
||||
|
||||
var added = await storage.Entries.AddAsync(picture.Entry, [picture.Media], ct).ConfigureAwait(false);
|
||||
return new SaveResult(added.Created ? SaveOutcome.Created : SaveOutcome.Known, added.Stored.Entry);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Completes an entry from the full data of its post («Post singolo»): adds the files that were missing, gives
|
||||
/// expired or failed files a fresh address (never for stories, spec §6.5 point 5), fills code and caption.
|
||||
/// Returns how many files were added or refreshed.
|
||||
/// </summary>
|
||||
public async Task<int> CompleteAsync(Entry entry, ContentItem item, Account account, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
var now = clock.Now;
|
||||
var current = await storage.Media.ListByEntryAsync(entry.Id, ct).ConfigureAwait(false);
|
||||
var positions = current.Select(m => m.Position).ToHashSet();
|
||||
var received = ReadMapping.ToMedia(item, now).Select(m => ApplyPolicy(account, entry.Kind, m)).ToList();
|
||||
var missing = received.Where(m => !positions.Contains(m.Position)).ToList();
|
||||
var changed = 0;
|
||||
if (missing.Count > 0)
|
||||
{
|
||||
await storage.Media.AddToEntryAsync(entry.Id, missing, ct).ConfigureAwait(false);
|
||||
changed += missing.Count;
|
||||
}
|
||||
|
||||
if (entry.Kind != EntryKind.Story)
|
||||
{
|
||||
foreach (var file in current.Where(m => m.State is MediaState.Expired or MediaState.Failed || (m.State == MediaState.ToDownload && m.SourceUrl is null)))
|
||||
{
|
||||
if (received.FirstOrDefault(r => r.Position == file.Position) is { SourceUrl: { } url } fresh)
|
||||
{
|
||||
await storage.Media.UpdateSourceAsync(file.Id, url, fresh.CoverUrl, now, ct).ConfigureAwait(false);
|
||||
changed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((entry.Code is null && item.Code is not null) || (entry.Caption is null && item.Caption is not null))
|
||||
{
|
||||
var latest = await storage.Entries.GetAsync(entry.Id, ct).ConfigureAwait(false) ?? entry;
|
||||
await storage.Entries.UpdateAsync(latest with { Code = latest.Code ?? item.Code, Caption = latest.Caption ?? item.Caption }, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records the highlight collections listed on a profile, in order; collections no longer listed are marked
|
||||
/// removed (their contents and files stay). Returns the stored collections by Instagram id.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyDictionary<string, Highlight>> UpsertHighlightsAsync(Account account, IReadOnlyList<HighlightInfo> listed, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentNullException.ThrowIfNull(listed);
|
||||
var now = clock.Now;
|
||||
var stored = new Dictionary<string, Highlight>(StringComparer.Ordinal);
|
||||
for (var i = 0; i < listed.Count; i++)
|
||||
{
|
||||
var info = listed[i];
|
||||
var existing = await storage.Highlights.FindAsync(account.Id, info.Id, ct).ConfigureAwait(false);
|
||||
var record = existing is null
|
||||
? ReadMapping.ToHighlight(info, account.Id, i, now)
|
||||
: existing with { Title = string.IsNullOrWhiteSpace(info.Title) ? existing.Title : info.Title.Trim(), Position = i, RemovedAt = null };
|
||||
stored[info.Id] = await storage.Highlights.UpsertAsync(record, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (stored.Count > 0)
|
||||
{
|
||||
foreach (var old in await storage.Highlights.ListAsync(account.Id, includeRemoved: false, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (old.InstagramId is not null && !stored.ContainsKey(old.InstagramId))
|
||||
{
|
||||
await storage.Highlights.MarkRemovedAsync(old.Id, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return stored;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts an item shown in a collection into it. A story already saved with the same identifier is referenced, not
|
||||
/// downloaded again (H9); otherwise the item becomes an entry of kind «evidenza». Returns the entry, or null when
|
||||
/// the account does not want highlights.
|
||||
/// </summary>
|
||||
public async Task<(Entry? Entry, bool Created)> LinkHighlightItemAsync(Account account, Highlight highlight, ContentItem item, long? sessionId, CancellationToken ct)
|
||||
{
|
||||
var existing = await storage.Entries.FindByInstagramIdAsync(account.Id, item.Id, ct).ConfigureAwait(false);
|
||||
var reuse = existing.FirstOrDefault(e => e.Kind == EntryKind.Story) ?? existing.FirstOrDefault(e => e.Kind == EntryKind.Highlight);
|
||||
var created = false;
|
||||
if (reuse is null)
|
||||
{
|
||||
var saved = await SaveAsync(account, item, EntryKind.Highlight, sessionId, ct).ConfigureAwait(false);
|
||||
reuse = saved.Entry;
|
||||
created = saved.Outcome == SaveOutcome.Created;
|
||||
}
|
||||
|
||||
if (reuse is not null)
|
||||
{
|
||||
await storage.Highlights.AddItemAsync(highlight.Id, reuse.Id, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return (reuse, created);
|
||||
}
|
||||
|
||||
/// <summary>Queues «Post singolo» for an entry (payload: the local entry id as text).</summary>
|
||||
public Task<EngineTask> QueueSinglePostAsync(Entry entry, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
var now = clock.Now;
|
||||
return storage.Tasks.EnqueueAsync(
|
||||
new EngineTask
|
||||
{
|
||||
Kind = EngineTaskKind.SinglePost,
|
||||
AccountId = entry.AccountId,
|
||||
DueAt = now,
|
||||
Payload = entry.Id.ToString(CultureInfo.InvariantCulture),
|
||||
CreatedAt = now,
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
/// <summary>Appends a line to the readable timeline (Italian; never captions, bodies or signed addresses).</summary>
|
||||
public Task EventAsync(string code, string message, EventSeverity severity, long? accountId, long? sessionId, CancellationToken ct) =>
|
||||
storage.Events.AppendAsync(
|
||||
new EventRecord
|
||||
{
|
||||
At = clock.Now,
|
||||
Severity = severity,
|
||||
Code = code,
|
||||
Message = message,
|
||||
AccountId = accountId,
|
||||
SessionId = sessionId,
|
||||
},
|
||||
ct);
|
||||
|
||||
private static Media ApplyPolicy(Account account, EntryKind kind, Media media) =>
|
||||
SkipReason(account, kind, media.Kind) is { } reason
|
||||
? media with { State = MediaState.Skipped, SourceUrl = null, CoverUrl = null, LastError = reason }
|
||||
: media;
|
||||
|
||||
private async Task RefreshExpiredAsync(Entry known, ContentItem item, CancellationToken ct)
|
||||
{
|
||||
if (known.State is EntryState.Deleted)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var files = await storage.Media.ListByEntryAsync(known.Id, ct).ConfigureAwait(false);
|
||||
var expired = files.Where(f => f.State == MediaState.Expired).ToList();
|
||||
if (expired.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var now = clock.Now;
|
||||
var received = ReadMapping.ToMedia(item, now);
|
||||
foreach (var file in expired)
|
||||
{
|
||||
if (received.FirstOrDefault(r => r.Position == file.Position) is { SourceUrl: { } url } fresh)
|
||||
{
|
||||
await storage.Media.UpdateSourceAsync(file.Id, url, fresh.CoverUrl, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
/// <summary>Outcome of looking a target up or clicking it.</summary>
|
||||
public enum TargetCheckStatus
|
||||
{
|
||||
Found,
|
||||
|
||||
/// <summary>Clicked (for <see cref="IPageDriver.ClickAsync"/>).</summary>
|
||||
Clicked,
|
||||
|
||||
NotFound,
|
||||
|
||||
NotVisible,
|
||||
|
||||
OutOfView,
|
||||
|
||||
Obstructed,
|
||||
|
||||
/// <summary>The map has the entry but it is still empty (H11).</summary>
|
||||
NotConfigured,
|
||||
}
|
||||
|
||||
/// <summary>Result of a target lookup or click. When not found, recipes stop and report: never coordinates (spec §7.7).</summary>
|
||||
/// <param name="Id">Target identifier of the map.</param>
|
||||
/// <param name="Status">What happened.</param>
|
||||
/// <param name="Matches">Visible matches found.</param>
|
||||
/// <param name="Message">Italian message for events, without page content.</param>
|
||||
public sealed record TargetCheck(string Id, TargetCheckStatus Status, int Matches, string Message)
|
||||
{
|
||||
public bool Found => Status is TargetCheckStatus.Found or TargetCheckStatus.Clicked;
|
||||
}
|
||||
|
||||
/// <summary>Result of opening a page.</summary>
|
||||
/// <param name="Succeeded">The page was loaded.</param>
|
||||
/// <param name="Path">Path of the page now shown (no query string).</param>
|
||||
/// <param name="Error">Browser error, without the address.</param>
|
||||
public sealed record PageLoad(bool Succeeded, string Path, string? Error);
|
||||
|
||||
/// <summary>
|
||||
/// What a recipe can do with the page (spec §6.3): open pages of the site, find and click targets of the target map,
|
||||
/// scroll with human gestures, wait, and read the state of the page without changing it. Implemented over the browser
|
||||
/// layer (<c>Febe.Browser.Recipes.BrowserPageDriver</c>); a fake implementation drives the simulation and unit tests.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Gestures go through <c>Input</c> only and never through scripts; a missing target is reported, never replaced by
|
||||
/// coordinates; the driver refuses to open addresses outside the site. Counting actions is not the driver's job: the
|
||||
/// recipe asks the Governor before every counted action.
|
||||
/// </remarks>
|
||||
public interface IPageDriver
|
||||
{
|
||||
/// <summary>Product of mood and gesture pace: multiplies the waits the recipes compute themselves (§7.7).</summary>
|
||||
double WaitMultiplier { get; }
|
||||
|
||||
/// <summary>A new session starts: gestures use its mood from now on.</summary>
|
||||
void BeginSession(double mood);
|
||||
|
||||
/// <summary>Opens a page of the site by path (starting with «/»), and waits until it is loaded and painted.</summary>
|
||||
Task<PageLoad> OpenAsync(string path, CancellationToken ct);
|
||||
|
||||
/// <summary>Path of the current page (no query string), read without changing anything.</summary>
|
||||
Task<string> CurrentPathAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>True when the current page belongs to the site (links outside the site are never followed).</summary>
|
||||
Task<bool> IsOnSiteAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>Looks a target up, read-only.</summary>
|
||||
Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct);
|
||||
|
||||
/// <summary>Clicks a target with a human gesture (bringing it into view with the wheel if needed).</summary>
|
||||
Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct);
|
||||
|
||||
/// <summary>One burst of wheel events down, the pause after it, and now and then a small scroll back (§7.7).</summary>
|
||||
Task ScrollBurstAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>The wait after a page load before the first gesture (median 2.2 s, 1–6 s).</summary>
|
||||
Task WaitAfterLoadAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>Waits <paramref name="duration"/> (already multiplied by the recipe when needed).</summary>
|
||||
Task WaitAsync(TimeSpan duration, CancellationToken ct);
|
||||
|
||||
/// <summary>With 8% probability, an extra wait of 15–90 s after an action.</summary>
|
||||
Task<bool> MaybeDistractionAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>Whether the session cookie exists (never its value); null when it cannot be told.</summary>
|
||||
Task<bool?> HasSessionCookieAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>The rest page (spec §6.1).</summary>
|
||||
Task RestAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remaining budget of a category (spec §6.3: before opening the stories of an account the recipe checks that the
|
||||
/// budget allows at least ten). Implemented by the Governor of the engine; tests use a permissive fake.
|
||||
/// </summary>
|
||||
public interface IBudgetView
|
||||
{
|
||||
/// <summary>Actions of <paramref name="kind"/> still allowed now (the stricter of hour and day, account limits included).</summary>
|
||||
Task<int> RemainingAsync(ActionKind kind, long? accountId, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Pacing;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
/// <summary>Limits and technical timeouts of the recipes. Times are measured with <see cref="IClock"/>.</summary>
|
||||
public sealed record RecipeOptions
|
||||
{
|
||||
/// <summary>How long to wait for the data of a page after opening it or after a gesture.</summary>
|
||||
public TimeSpan DataTimeout { get; init; } = TimeSpan.FromSeconds(20);
|
||||
|
||||
/// <summary>Quiet time without new data responses that counts as «the page has settled».</summary>
|
||||
public TimeSpan SettleQuiet { get; init; } = TimeSpan.FromMilliseconds(700);
|
||||
|
||||
/// <summary>How long to wait for the viewer to open, move on or close after a click.</summary>
|
||||
public TimeSpan ViewerTimeout { get; init; } = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>Polling interval of read-only checks.</summary>
|
||||
public TimeSpan Poll { get; init; } = TimeSpan.FromMilliseconds(100);
|
||||
|
||||
/// <summary>Giro dei seguiti: at most this many scroll bursts (spec §6.3: 8).</summary>
|
||||
public int SweepMaxBursts { get; init; } = 8;
|
||||
|
||||
/// <summary>Scroll bursts allowed to bring in one more page of data before giving up.</summary>
|
||||
public int BurstsPerPage { get; init; } = 12;
|
||||
|
||||
/// <summary>Pages of history per run when the request does not say (Storico, Taggati, Reel).</summary>
|
||||
public int PagesPerRun { get; init; } = 3;
|
||||
|
||||
/// <summary>Pages of the following list per run when the request does not say.</summary>
|
||||
public int FollowingPagesPerRun { get; init; } = 5;
|
||||
|
||||
/// <summary>Stories are opened only when the budget allows at least this many (spec §6.3: ten).</summary>
|
||||
public int MinStoryBudget { get; init; } = 10;
|
||||
|
||||
/// <summary>The backfill stops while the account has more files than this waiting for download (spec §6.3: 60).</summary>
|
||||
public int MaxPendingDownloadsForBackfill { get; init; } = 60;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The story timings of spec §7.7, for the «naturale» pace: photos 1.8–5 s; videos 40–100% of their duration, at most
|
||||
/// 15 s; 1–4 s between one account and the next. Every value is multiplied by mood and pace.
|
||||
/// </summary>
|
||||
public static class StoryTimings
|
||||
{
|
||||
public static readonly TimeSpan PhotoMin = TimeSpan.FromSeconds(1.8);
|
||||
public static readonly TimeSpan PhotoMax = TimeSpan.FromSeconds(5);
|
||||
public static readonly TimeSpan VideoMax = TimeSpan.FromSeconds(15);
|
||||
public static readonly TimeSpan BetweenAccountsMin = TimeSpan.FromSeconds(1);
|
||||
public static readonly TimeSpan BetweenAccountsMax = TimeSpan.FromSeconds(4);
|
||||
|
||||
/// <summary>How long to watch a story before moving on.</summary>
|
||||
/// <param name="random">Random source.</param>
|
||||
/// <param name="videoDuration">Duration of the video, or null for a photo (or a video of unknown length).</param>
|
||||
/// <param name="multiplier">Mood × pace.</param>
|
||||
public static TimeSpan Watch(IRandomSource random, TimeSpan? videoDuration, double multiplier)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(random);
|
||||
TimeSpan wait;
|
||||
if (videoDuration is { } duration && duration > TimeSpan.Zero)
|
||||
{
|
||||
var fraction = random.Between(0.4, 1.0);
|
||||
wait = TimeSpan.FromTicks(Math.Min((long)(duration.Ticks * fraction), VideoMax.Ticks));
|
||||
}
|
||||
else
|
||||
{
|
||||
wait = random.Between(PhotoMin, PhotoMax);
|
||||
}
|
||||
|
||||
return TimeSpan.FromTicks((long)(wait.Ticks * multiplier));
|
||||
}
|
||||
|
||||
/// <summary>The pause between the stories of one account and those of the next.</summary>
|
||||
public static TimeSpan BetweenAccounts(IRandomSource random, double multiplier) =>
|
||||
TimeSpan.FromTicks((long)(random.Between(BetweenAccountsMin, BetweenAccountsMax).Ticks * multiplier));
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
/// <summary>Stops a recipe where it is, with a status and an Italian message (internal control flow).</summary>
|
||||
internal sealed class RecipeStopException(RecipeStatus status, string message) : Exception(message)
|
||||
{
|
||||
public RecipeStatus Status { get; } = status;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The state of one recipe run: counted actions, new entries, the first stop signal seen, and the helpers every
|
||||
/// recipe uses (ask the Governor, open a page, click a target, wait for data). Any of them stops the run with a
|
||||
/// <see cref="RecipeStopException"/> when something says to stop.
|
||||
/// </summary>
|
||||
internal sealed class RecipeRun : IDisposable
|
||||
{
|
||||
private readonly RecipeRunner _runner;
|
||||
private readonly IStopSignals _signals;
|
||||
private Signal? _signal;
|
||||
|
||||
public RecipeRun(RecipeRunner runner, RecipeRequest request, ISessionContext session, CancellationToken ct)
|
||||
{
|
||||
_runner = runner;
|
||||
Request = request;
|
||||
Session = session;
|
||||
Ct = ct;
|
||||
_signals = runner.Env.Signals;
|
||||
_signals.SignalRaised += OnSignal;
|
||||
}
|
||||
|
||||
public RecipeRequest Request { get; }
|
||||
|
||||
public ISessionContext Session { get; }
|
||||
|
||||
public CancellationToken Ct { get; }
|
||||
|
||||
public int Actions { get; set; }
|
||||
|
||||
public int NewEntries { get; set; }
|
||||
|
||||
public HashSet<long> AccountsWithStories { get; } = [];
|
||||
|
||||
public HashSet<long> AccountsWithNewPosts { get; } = [];
|
||||
|
||||
public bool Finished { get; set; }
|
||||
|
||||
/// <summary>The first stop signal raised since the run started.</summary>
|
||||
public Signal? Signal => Volatile.Read(ref _signal);
|
||||
|
||||
/// <summary>Key structures of unrecognized responses seen in the run.</summary>
|
||||
public List<string> UnknownShapes { get; } = [];
|
||||
|
||||
private RecipeEnvironment Env => _runner.Env;
|
||||
|
||||
public void Dispose() => _signals.SignalRaised -= OnSignal;
|
||||
|
||||
public static RecipeStopException Stop(RecipeStatus status, string message) => new(status, message);
|
||||
|
||||
/// <summary>Stops the run when a signal was raised or the breaker is open.</summary>
|
||||
public void ThrowIfSignal()
|
||||
{
|
||||
if (Signal is { } signal)
|
||||
{
|
||||
throw Stop(RecipeStatus.StoppedBySignal, RecipeRunner.Describe(signal));
|
||||
}
|
||||
|
||||
if (Env.Breaker is { } breaker && !breaker.State.AllowsSiteActions)
|
||||
{
|
||||
throw Stop(RecipeStatus.StoppedBySignal, breaker.State.LastSignal is { } last ? RecipeRunner.Describe(last) : "L'interruttore è aperto: la ricetta si ferma.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Asks the Governor for a counted action; stops in order when refused or when the session is over.</summary>
|
||||
public async Task PermitAsync(ActionKind kind, long? accountId)
|
||||
{
|
||||
ThrowIfSignal();
|
||||
if (Env.Clock.Now > Session.PlannedEnd)
|
||||
{
|
||||
throw Stop(RecipeStatus.Denied, "La sessione è finita: la ricetta riprenderà alla prossima.");
|
||||
}
|
||||
|
||||
var permit = await Env.Governor.RequestAsync(kind, accountId, Ct).ConfigureAwait(false);
|
||||
if (!permit.Granted)
|
||||
{
|
||||
throw Stop(RecipeStatus.Denied, permit.Message ?? $"Il Governatore non ha concesso l'azione ({permit.Reason}).");
|
||||
}
|
||||
|
||||
Actions++;
|
||||
}
|
||||
|
||||
/// <summary>Opens a page of the site map and waits after the load like a person (§7.7).</summary>
|
||||
public async Task<PageLoad> OpenAsync(string page, IReadOnlyDictionary<string, string>? values = null)
|
||||
{
|
||||
var path = Env.SiteMap.BuildPath(page, values);
|
||||
var load = await Env.Driver.OpenAsync(path, Ct).ConfigureAwait(false);
|
||||
ThrowIfSignal();
|
||||
if (!load.Succeeded)
|
||||
{
|
||||
throw Stop(RecipeStatus.Failed, $"La pagina non si è caricata ({load.Error ?? "errore sconosciuto"}).");
|
||||
}
|
||||
|
||||
await EnsureOnSiteAsync().ConfigureAwait(false);
|
||||
await Env.Driver.WaitAfterLoadAsync(Ct).ConfigureAwait(false);
|
||||
ThrowIfSignal();
|
||||
return load;
|
||||
}
|
||||
|
||||
/// <summary>Clicks a target of the map; stops and reports when it cannot be found (never coordinates).</summary>
|
||||
public async Task ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters = null)
|
||||
{
|
||||
ThrowIfSignal();
|
||||
var result = await Env.Driver.ClickAsync(target, parameters, Ct).ConfigureAwait(false);
|
||||
if (!result.Found)
|
||||
{
|
||||
ThrowIfSignal();
|
||||
throw Stop(RecipeStatus.TargetNotFound, result.Message);
|
||||
}
|
||||
|
||||
ThrowIfSignal();
|
||||
await EnsureOnSiteAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Read-only lookup of a target.</summary>
|
||||
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters = null) =>
|
||||
Env.Driver.FindAsync(target, parameters, Ct);
|
||||
|
||||
/// <summary>The page must still be on the site: links outside it are never followed (spec §6.1).</summary>
|
||||
public async Task EnsureOnSiteAsync()
|
||||
{
|
||||
if (!await Env.Driver.IsOnSiteAsync(Ct).ConfigureAwait(false))
|
||||
{
|
||||
ThrowIfSignal();
|
||||
throw Stop(RecipeStatus.Failed, "La pagina ha portato fuori dal sito: la ricetta si ferma e non segue collegamenti esterni.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits for reads after <paramref name="mark"/> that satisfy <paramref name="expected"/>, or for a stop signal.</summary>
|
||||
public async Task<IReadOnlyList<CapturedRead>> WaitForDataAsync(long mark, Func<ReadResult, bool> expected, TimeSpan? timeout = null)
|
||||
{
|
||||
var reads = await Env.Capture.WaitAsync(
|
||||
mark,
|
||||
r => Signal is not null || r.Any(x => x.Result.Shape == ReadShape.Recognized && expected(x.Result)),
|
||||
timeout ?? Env.Options.DataTimeout,
|
||||
Env.Options.Poll,
|
||||
Ct).ConfigureAwait(false);
|
||||
ThrowIfSignal();
|
||||
return reads;
|
||||
}
|
||||
|
||||
/// <summary>Waits until no data response is on its way any more.</summary>
|
||||
public async Task SettleAsync()
|
||||
{
|
||||
await Env.Capture.SettleAsync(Env.Options.SettleQuiet, Env.Options.DataTimeout, Env.Options.Poll, Ct).ConfigureAwait(false);
|
||||
ThrowIfSignal();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Judges the reads of a step that expected <paramref name="expected"/>: recognized data resets the empty-page
|
||||
/// counter; only unknown shapes stop the run with <see cref="RecipeStatus.UnrecognizedFormat"/>; nothing at all is
|
||||
/// an empty page (three in a row raise a throttle signal). Returns true when the expected data arrived.
|
||||
/// </summary>
|
||||
public bool Judge(IReadOnlyList<CapturedRead> reads, Func<ReadResult, bool> expected, string? where)
|
||||
{
|
||||
if (reads.Any(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result)))
|
||||
{
|
||||
_signals.ObserveNonEmptyPage();
|
||||
return true;
|
||||
}
|
||||
|
||||
var unknown = reads.Where(r => r.Result.Shape == ReadShape.Unrecognized && r.Result.KeyStructure is not null).Select(r => r.Result.KeyStructure!).Distinct().ToList();
|
||||
if (unknown.Count > 0)
|
||||
{
|
||||
UnknownShapes.AddRange(unknown);
|
||||
throw Stop(RecipeStatus.UnrecognizedFormat, "La risposta del sito ha una forma che i lettori non riconoscono.");
|
||||
}
|
||||
|
||||
_signals.ObserveEmptyPage(where);
|
||||
ThrowIfSignal();
|
||||
return false;
|
||||
}
|
||||
|
||||
private void OnSignal(object? sender, Signal signal) => Interlocked.CompareExchange(ref _signal, signal, null);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
public sealed partial class RecipeRunner
|
||||
{
|
||||
/// <summary>Setting keys of the following list reading, which may span several sessions (spec §4.2).</summary>
|
||||
public static class FollowingKeys
|
||||
{
|
||||
public const string Cursor = "seguiti.cursore";
|
||||
public const string StartedAt = "seguiti.inizio";
|
||||
public const string Read = "seguiti.letti";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Post singolo (spec §6.3, §6.5 point 5): opens the page of a post (1 counted action) when the grid did not give
|
||||
/// all its files, or to get a fresh address for a file whose address expired. Never for stories.
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> SinglePostAsync(RecipeRun run)
|
||||
{
|
||||
if (run.Request.EntryId is not { } entryId)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "«Post singolo» ha bisogno dell'elemento da completare.");
|
||||
}
|
||||
|
||||
var entry = await Env.Storage.Entries.GetAsync(entryId, run.Ct).ConfigureAwait(false)
|
||||
?? throw RecipeRun.Stop(RecipeStatus.Failed, $"Elemento {entryId} non trovato.");
|
||||
if (entry.Kind is EntryKind.Story or EntryKind.Highlight or EntryKind.ProfilePicture)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, "Per storie, raccolte e foto del profilo non c'è una pagina del post: nessun recupero.");
|
||||
}
|
||||
|
||||
if (entry.State == EntryState.Deleted || entry.Code is null)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, entry.Code is null ? "L'elemento non ha un codice: non si può aprire la sua pagina." : "Elemento eliminato: non si riscarica.");
|
||||
}
|
||||
|
||||
var account = await Env.Storage.Accounts.GetAsync(entry.AccountId, run.Ct).ConfigureAwait(false)
|
||||
?? throw RecipeRun.Stop(RecipeStatus.Failed, $"Account {entry.AccountId} non trovato.");
|
||||
if (account.State == AccountState.ArchiveOnly)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Denied, $"{account.Username} è «Solo archivio»: non si contatta.");
|
||||
}
|
||||
|
||||
await run.PermitAsync(ActionKind.SinglePost, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Post, Values(("code", entry.Code))).ConfigureAwait(false);
|
||||
bool Matches(Readers.ContentItem c) => c.Id == entry.InstagramId || (c.Code is not null && c.Code == entry.Code);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Contents.Any(Matches)).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Contents.Any(Matches), Env.SiteMap.BuildPath(SitePages.Post, Values(("code", entry.Code)))))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, "La pagina del post non ha dato il post: forse non esiste più.");
|
||||
}
|
||||
|
||||
var item = Contents(reads, Matches).First();
|
||||
var changed = await Writer.CompleteAsync(entry, item, account, run.Ct).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, changed == 0 ? "Post già completo." : $"Post completato: {changed} file da scaricare.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Elenco dei seguiti (spec §4.2, §6.3): reads the list of the profiles Alberto follows, one page per permit,
|
||||
/// over as many sessions as needed; the progress is stored («Letti 96 profili, continuo alla prossima sessione»).
|
||||
/// <see cref="RecipeOutcome.BackfillFinished"/> is true when the end of the list was reached.
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> FollowingListAsync(RecipeRun run)
|
||||
{
|
||||
var mine = await Env.Storage.Accounts.GetMineAsync(run.Ct).ConfigureAwait(false)
|
||||
?? throw RecipeRun.Stop(RecipeStatus.Failed, "Non conosco ancora il profilo collegato: serve prima un giro dei seguiti.");
|
||||
var settings = Env.Storage.Settings;
|
||||
var cursor = await settings.GetAsync(FollowingKeys.Cursor, run.Ct).ConfigureAwait(false);
|
||||
var started = DateTimeOffset.TryParse(await settings.GetAsync(FollowingKeys.StartedAt, run.Ct).ConfigureAwait(false), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var s) ? s : (DateTimeOffset?)null;
|
||||
var read = (int)(await settings.GetInt64Async(FollowingKeys.Read, run.Ct).ConfigureAwait(false) ?? 0);
|
||||
var resume = cursor is not null && started is not null && Env.SiteMap.HasPage(SitePages.FollowingFrom);
|
||||
if (!resume)
|
||||
{
|
||||
cursor = null;
|
||||
read = 0;
|
||||
started = Env.Clock.Now;
|
||||
}
|
||||
|
||||
var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.FollowingPagesPerRun);
|
||||
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(
|
||||
resume ? SitePages.FollowingFrom : SitePages.Following,
|
||||
resume ? Values(("username", mine.Username), ("cursor", cursor!)) : Values(("username", mine.Username))).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Profiles.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Profiles.Count > 0, null))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
var pages = 1;
|
||||
var finished = false;
|
||||
while (true)
|
||||
{
|
||||
read += await SaveFollowingPageAsync(run, reads, mine, read).ConfigureAwait(false);
|
||||
var page = LastPage(reads);
|
||||
cursor = page?.Cursor ?? cursor;
|
||||
if (page?.HasMore == false)
|
||||
{
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (pages >= maxPages)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false);
|
||||
reads = await ScrollForPageAsync(run, r => r.Profiles.Count > 0).ConfigureAwait(false);
|
||||
pages++;
|
||||
if (reads.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (finished)
|
||||
{
|
||||
var removed = await Env.Storage.Following.RemoveNotReadSinceAsync(started!.Value, run.Ct).ConfigureAwait(false);
|
||||
await settings.SetManyAsync(
|
||||
new Dictionary<string, string?> { [FollowingKeys.Cursor] = null, [FollowingKeys.StartedAt] = null, [FollowingKeys.Read] = null },
|
||||
run.Ct).ConfigureAwait(false);
|
||||
run.Finished = true;
|
||||
var message = $"Elenco dei seguiti letto: {ItalianText.Number(read)} profili" + (removed > 0 ? $", {ItalianText.Number(removed)} non più seguiti." : ".");
|
||||
await Writer.EventAsync("seguiti-letti", message, EventSeverity.Success, null, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, message);
|
||||
}
|
||||
|
||||
await settings.SetManyAsync(
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
[FollowingKeys.Cursor] = cursor,
|
||||
[FollowingKeys.StartedAt] = started!.Value.ToString("O", CultureInfo.InvariantCulture),
|
||||
[FollowingKeys.Read] = read.ToString(CultureInfo.InvariantCulture),
|
||||
},
|
||||
run.Ct).ConfigureAwait(false);
|
||||
var progress = $"Letti {ItalianText.Number(read)} profili, continuo alla prossima sessione";
|
||||
await Writer.EventAsync("seguiti-parziale", progress, EventSeverity.Info, null, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, progress);
|
||||
}
|
||||
|
||||
/// <summary>Stores one page of the following list in reading order; renamed followed accounts are recognized.</summary>
|
||||
private async Task<int> SaveFollowingPageAsync(RecipeRun run, IReadOnlyList<CapturedRead> reads, Account mine, int offset)
|
||||
{
|
||||
var now = Env.Clock.Now;
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
var profiles = reads.SelectMany(r => r.Result.Profiles).Where(p => !p.IsViewer && p.Id != mine.InstagramId && seen.Add(p.Id)).ToList();
|
||||
var records = new List<FollowingRecord>(profiles.Count);
|
||||
for (var i = 0; i < profiles.Count; i++)
|
||||
{
|
||||
var p = profiles[i];
|
||||
records.Add(new FollowingRecord
|
||||
{
|
||||
InstagramId = p.Id,
|
||||
Username = p.Username,
|
||||
DisplayName = p.DisplayName,
|
||||
IsPrivate = p.IsPrivate,
|
||||
Position = offset + i,
|
||||
ReadAt = now,
|
||||
});
|
||||
if (await Writer.ObserveProfileAsync(p with { IsFollowed = true }, run.Session.SessionId, run.Ct).ConfigureAwait(false) is { IsFollowed: false } account)
|
||||
{
|
||||
await Env.Storage.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { IsFollowed = true }, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (records.Count > 0)
|
||||
{
|
||||
await Env.Storage.Following.UpsertAsync(records, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return records.Count;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
public sealed partial class RecipeRunner
|
||||
{
|
||||
/// <summary>A walk through the pages of a profile tab (Storico on the grid, Taggati, Reel).</summary>
|
||||
private sealed record ProfileWalk(EntryKind Kind, string? TabTarget, string ResumePage, string SettingPrefix)
|
||||
{
|
||||
public static readonly ProfileWalk Posts = new(EntryKind.Post, null, SitePages.ProfileFrom, "raccolta.post");
|
||||
public static readonly ProfileWalk Tagged = new(EntryKind.Tagged, SiteTargets.ProfileTabTagged, SitePages.TaggedFrom, "raccolta.taggati");
|
||||
public static readonly ProfileWalk Reels = new(EntryKind.Post, SiteTargets.ProfileTabReels, SitePages.ReelsFrom, "raccolta.reel");
|
||||
|
||||
public bool IsGrid => TabTarget is null;
|
||||
|
||||
public string CursorKey(long accountId) => $"{SettingPrefix}.{accountId.ToString(CultureInfo.InvariantCulture)}.cursore";
|
||||
|
||||
public string CompletedKey(long accountId) => $"{SettingPrefix}.{accountId.ToString(CultureInfo.InvariantCulture)}.completo";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Controllo del profilo (spec §6.3): opens the profile (1 counted action), reads its state, the first page of
|
||||
/// posts and the list of highlight collections, keeps a copy of the profile picture when it changes, and stops at
|
||||
/// known content. Pinned posts are recognized and skipped for the stop rule.
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> ProfileCheckAsync(RecipeRun run)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
var (current, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false);
|
||||
account = current;
|
||||
var profile = FindProfile(reads, account)!;
|
||||
|
||||
if (profile.LatestStoryAt is { } latest && latest > (account.LastStoriesCheckAt ?? DateTimeOffset.MinValue)
|
||||
&& account.ContentTypes.HasFlag(ContentTypes.Stories))
|
||||
{
|
||||
run.AccountsWithStories.Add(account.Id);
|
||||
}
|
||||
|
||||
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => h.Owner is null || h.Owner.Id == account.InstagramId).ToList();
|
||||
await Writer.UpsertHighlightsAsync(account, listed, run.Ct).ConfigureAwait(false);
|
||||
|
||||
if ((await Writer.SaveProfilePictureAsync(account, profile, run.Ct).ConfigureAwait(false)).Outcome == SaveOutcome.Created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
}
|
||||
|
||||
var reachedKnown = false;
|
||||
foreach (var item in Contents(reads, c => IsOwnedBy(c, account)))
|
||||
{
|
||||
var saved = await Writer.SaveAsync(account, item, EntryKind.Post, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
if (saved.Outcome == SaveOutcome.Created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
run.AccountsWithNewPosts.Add(account.Id);
|
||||
}
|
||||
else if (saved.Outcome == SaveOutcome.Known && !item.Pinned)
|
||||
{
|
||||
reachedKnown = true; // pinned posts are known but do not stop the check
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var page = LastPage(reads);
|
||||
if (!reachedKnown && account.BackfillCompletedAt is null && account.BackfillCursor is null)
|
||||
{
|
||||
if (page?.HasMore == true && page.Cursor is { } cursor)
|
||||
{
|
||||
await Env.Storage.Accounts.SetBackfillAsync(account.Id, cursor, null, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
else if (page?.HasMore == false)
|
||||
{
|
||||
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Storico, Taggati and Reel (spec §6.3): one page per permit, resuming from the stored point and stopping at the
|
||||
/// beginning of the profile. The backfill stops while the account has more than 60 files waiting for download or
|
||||
/// the data budget is used up (the engine checks too, the recipe must stop as well). Once a tab has been walked to
|
||||
/// the end, later runs only check its first page and stop at known content.
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> WalkAsync(RecipeRun run, ProfileWalk walk)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
if (!CollectionWriter.Wants(account, walk.Kind))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, walk.Kind == EntryKind.Tagged
|
||||
? $"«Post in cui è taggato» è spento per {account.Username}."
|
||||
: $"Foto e video dei post sono spenti per {account.Username}.");
|
||||
}
|
||||
|
||||
var settings = Env.Storage.Settings;
|
||||
string? cursor;
|
||||
bool checkOnly;
|
||||
if (walk.IsGrid)
|
||||
{
|
||||
if (account.BackfillCompletedAt is not null)
|
||||
{
|
||||
run.Finished = true;
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
cursor = account.BackfillCursor;
|
||||
checkOnly = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
cursor = await settings.GetAsync(walk.CursorKey(account.Id), run.Ct).ConfigureAwait(false);
|
||||
checkOnly = await settings.GetAsync(walk.CompletedKey(account.Id), run.Ct).ConfigureAwait(false) is not null;
|
||||
if (checkOnly)
|
||||
{
|
||||
cursor = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!checkOnly)
|
||||
{
|
||||
await EnsureBackfillAllowedAsync(run, account).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.PagesPerRun);
|
||||
var parameters = Values(("username", account.Username));
|
||||
IReadOnlyList<CapturedRead> reads;
|
||||
var pages = 0;
|
||||
if (cursor is not null && Env.SiteMap.HasPage(walk.ResumePage))
|
||||
{
|
||||
// Resume where the last run stopped: the page of the site that starts after the stored point.
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", cursor))).ConfigureAwait(false);
|
||||
reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
pages++;
|
||||
}
|
||||
else
|
||||
{
|
||||
(account, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false);
|
||||
if (walk.TabTarget is { } tab)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.ClickAsync(tab, parameters).ConfigureAwait(false);
|
||||
await Env.Driver.WaitAfterLoadAsync(run.Ct).ConfigureAwait(false);
|
||||
reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, null))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
pages++;
|
||||
}
|
||||
}
|
||||
|
||||
var finished = false;
|
||||
var processed = new HashSet<string>(StringComparer.Ordinal);
|
||||
while (true)
|
||||
{
|
||||
var (reachedKnown, reachedLimit) = await SaveWalkPageAsync(run, account, walk, reads, processed, stopAtKnown: checkOnly).ConfigureAwait(false);
|
||||
var page = LastPage(reads);
|
||||
if (reachedLimit || page?.HasMore == false)
|
||||
{
|
||||
finished = !checkOnly || page?.HasMore == false;
|
||||
break;
|
||||
}
|
||||
|
||||
if (checkOnly && reachedKnown)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
cursor = page?.Cursor ?? cursor;
|
||||
await StoreWalkCursorAsync(run, account, walk, cursor).ConfigureAwait(false);
|
||||
if (pages >= maxPages)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (!checkOnly)
|
||||
{
|
||||
await EnsureBackfillAllowedAsync(run, account).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
reads = await ScrollForPageAsync(run, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
pages++;
|
||||
if (reads.Count == 0)
|
||||
{
|
||||
break; // nothing came in after the bursts (counted as an empty page)
|
||||
}
|
||||
}
|
||||
|
||||
if (finished)
|
||||
{
|
||||
run.Finished = true;
|
||||
if (walk.IsGrid)
|
||||
{
|
||||
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
|
||||
await Writer.EventAsync("storico-completato", $"Storico di {account.Username} completato.", EventSeverity.Success, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await settings.SetManyAsync(
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
[walk.CursorKey(account.Id)] = null,
|
||||
[walk.CompletedKey(account.Id)] = Env.Clock.Now.ToString("O", CultureInfo.InvariantCulture),
|
||||
},
|
||||
run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the new items of a walk page. Returns whether known content was met (only meaningful when
|
||||
/// <paramref name="stopAtKnown"/>) and whether a history limit of the account was reached (from a date, last N posts).
|
||||
/// </summary>
|
||||
private async Task<(bool ReachedKnown, bool ReachedLimit)> SaveWalkPageAsync(RecipeRun run, Account account, ProfileWalk walk, IReadOnlyList<CapturedRead> reads, HashSet<string> processed, bool stopAtKnown)
|
||||
{
|
||||
var items = Contents(reads, c => walk.Kind == EntryKind.Tagged ? !IsOwnedBy(c, account) : IsOwnedBy(c, account))
|
||||
.Where(c => processed.Add(c.Id))
|
||||
.ToList();
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (walk.Kind != EntryKind.Tagged && !item.Pinned)
|
||||
{
|
||||
if (account.Limits.Depth == HistoryDepth.FromDate && account.Limits.FromDate is { } from && item.TakenAt < from)
|
||||
{
|
||||
return (false, true);
|
||||
}
|
||||
|
||||
if (account.Limits.Depth == HistoryDepth.LastPosts && account.Limits.LastPosts is { } last
|
||||
&& await Env.Storage.Entries.ListByAccountAsync(account.Id, new Storage.EntryListOptions { Kind = EntryKind.Post, Limit = last }, run.Ct).ConfigureAwait(false) is { } kept
|
||||
&& kept.Count >= last)
|
||||
{
|
||||
return (false, true);
|
||||
}
|
||||
}
|
||||
|
||||
var saved = await Writer.SaveAsync(account, item, walk.Kind, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
if (saved.Outcome == SaveOutcome.Created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
run.AccountsWithNewPosts.Add(account.Id);
|
||||
}
|
||||
else if (stopAtKnown && saved.Outcome == SaveOutcome.Known && !item.Pinned)
|
||||
{
|
||||
return (true, false);
|
||||
}
|
||||
}
|
||||
|
||||
return (false, false);
|
||||
}
|
||||
|
||||
private async Task StoreWalkCursorAsync(RecipeRun run, Account account, ProfileWalk walk, string? cursor)
|
||||
{
|
||||
if (cursor is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (walk.IsGrid)
|
||||
{
|
||||
await Env.Storage.Accounts.SetBackfillAsync(account.Id, cursor, null, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await Env.Storage.Settings.SetAsync(walk.CursorKey(account.Id), cursor, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Lo storico non corre più veloce dei download» (spec §6.3): stops while the account has more than 60 files waiting
|
||||
/// or the data budget is used up.
|
||||
/// </summary>
|
||||
private async Task EnsureBackfillAllowedAsync(RecipeRun run, Account account)
|
||||
{
|
||||
var pending = await Env.Storage.Media.CountPendingDownloadsAsync(account.Id, run.Ct).ConfigureAwait(false);
|
||||
if (pending > Env.Options.MaxPendingDownloadsForBackfill)
|
||||
{
|
||||
await Writer.EventAsync("storico-sospeso", $"Storico di {account.Username} sospeso: {ItalianText.Number(pending)} file aspettano di essere scaricati.", EventSeverity.Info, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.Denied, $"Storico sospeso: {ItalianText.Number(pending)} file di {account.Username} aspettano di essere scaricati (più di {Env.Options.MaxPendingDownloadsForBackfill}).");
|
||||
}
|
||||
|
||||
if (Env.DataBudget is { } budget && await budget.RemainingTodayAsync(run.Ct).ConfigureAwait(false) <= 0)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Denied, "Storico sospeso: il tetto giornaliero dei dati scaricati è raggiunto.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the profile page (1 counted action) and reads its state: missing profile, a name now used by another
|
||||
/// account, private profile not followed (rule 6: not touched). Returns the updated account and the reads.
|
||||
/// </summary>
|
||||
private async Task<(Account Account, IReadOnlyList<CapturedRead> Reads)> OpenProfileAsync(RecipeRun run, Account account)
|
||||
{
|
||||
var parameters = Values(("username", account.Username));
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
if ((await run.FindAsync(SiteTargets.ProfileNotFound, parameters).ConfigureAwait(false)).Found)
|
||||
{
|
||||
await MarkUnreachableAsync(run, account, UnreachableReason.NotFound).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"Il profilo {account.Username} non esiste o non è più disponibile.");
|
||||
}
|
||||
|
||||
var reads = await run.WaitForDataAsync(mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => ProfileIn(r, account) is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
var profile = FindProfile(reads, account)!;
|
||||
if (account.InstagramId is { } known && profile.Id != known)
|
||||
{
|
||||
await MarkUnreachableAsync(run, account, UnreachableReason.Renamed).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"Il nome {account.Username} ora appartiene a un altro profilo: l'account resta com'era.");
|
||||
}
|
||||
|
||||
account = await Writer.ApplyProfileAsync(account, profile, run.Ct).ConfigureAwait(false);
|
||||
if (profile.IsPrivate == true && profile.IsFollowed == false)
|
||||
{
|
||||
await MarkUnreachableAsync(run, account, UnreachableReason.PrivateNotFollowed).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"{account.Username} è un profilo privato che non segui: non si tocca.");
|
||||
}
|
||||
|
||||
if (account.State == AccountState.Unreachable)
|
||||
{
|
||||
var state = account.BackfillCursor is not null && account.BackfillCompletedAt is null ? AccountState.Backfilling : AccountState.UpToDate;
|
||||
await Env.Storage.Accounts.SetStateAsync(account.Id, state, Env.Clock.Now, null, run.Ct).ConfigureAwait(false);
|
||||
await Writer.EventAsync("account-raggiungibile", $"{account.Username} è di nuovo raggiungibile.", EventSeverity.Info, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
account = await Env.Storage.Accounts.GetAsync(account.Id, run.Ct).ConfigureAwait(false) ?? account;
|
||||
}
|
||||
|
||||
return (account, reads);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scrolls with bursts until a new page of data that satisfies <paramref name="expected"/> arrives, at most
|
||||
/// <see cref="RecipeOptions.BurstsPerPage"/> bursts. Returns the reads of that page (empty when none came).
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<CapturedRead>> ScrollForPageAsync(RecipeRun run, Func<ReadResult, bool> expected)
|
||||
{
|
||||
var mark = Env.Capture.Mark();
|
||||
for (var burst = 0; burst < Env.Options.BurstsPerPage; burst++)
|
||||
{
|
||||
await Env.Driver.ScrollBurstAsync(run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
if (Env.Capture.Pending > 0 || Env.Capture.Since(mark).Count > 0)
|
||||
{
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var reads = Env.Capture.Since(mark);
|
||||
if (reads.Any(r => r.Result.Shape != ReadShape.Recognized || expected(r.Result)))
|
||||
{
|
||||
return run.Judge(reads, expected, null)
|
||||
? reads.Where(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result)).ToList()
|
||||
: [];
|
||||
}
|
||||
}
|
||||
|
||||
run.Judge([], expected, null);
|
||||
return [];
|
||||
}
|
||||
|
||||
/// <summary>Outcome message of a page that arrived without data (three in a row raise a throttle signal).</summary>
|
||||
private const string EmptyPageMessage = "La pagina è arrivata vuota: nessun dato da leggere.";
|
||||
|
||||
private static PageInfo? LastPage(IEnumerable<CapturedRead> reads) =>
|
||||
reads.Where(r => r.Result.Page is not null).Select(r => r.Result.Page).LastOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>Italian formatting for messages: thousands with a dot (spec: «48.212 elementi»).</summary>
|
||||
public static class ItalianText
|
||||
{
|
||||
public static string Number(long value)
|
||||
{
|
||||
var digits = Math.Abs(value).ToString(CultureInfo.InvariantCulture);
|
||||
var groups = new List<string>();
|
||||
for (var end = digits.Length; end > 0; end -= 3)
|
||||
{
|
||||
groups.Insert(0, digits[Math.Max(0, end - 3)..end]);
|
||||
}
|
||||
|
||||
return (value < 0 ? "-" : string.Empty) + string.Join('.', groups);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
public sealed partial class RecipeRunner
|
||||
{
|
||||
/// <summary>
|
||||
/// Giro dei seguiti (spec §6.3): opens the home (1 counted action), reads the stories bar, and scrolls the recent
|
||||
/// posts of followed profiles until it meets known content, with at most 8 bursts. Posts that arrive with complete
|
||||
/// data are saved at once; incomplete series are saved with what arrived and completed by «Post singolo».
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> FollowingSweepAsync(RecipeRun run)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.Home, null).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Home).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Profiles.Count > 0).ConfigureAwait(false);
|
||||
run.Judge(reads, r => r.Contents.Count > 0 || r.Profiles.Count > 0, Env.SiteMap.BuildPath(SitePages.Home));
|
||||
|
||||
var processed = 0;
|
||||
var sawKnown = await ProcessSweepReadsAsync(run, reads, ref processed).ConfigureAwait(false);
|
||||
var hasMore = reads.Select(r => r.Result.Page).LastOrDefault(p => p is not null)?.HasMore ?? true;
|
||||
|
||||
for (var burst = 0; burst < Env.Options.SweepMaxBursts && !sawKnown && hasMore; burst++)
|
||||
{
|
||||
var before = Env.Capture.Mark();
|
||||
await Env.Driver.ScrollBurstAsync(run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
var more = Env.Capture.Since(before);
|
||||
if (more.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
reads = [.. reads, .. more];
|
||||
sawKnown = await ProcessSweepReadsAsync(run, reads, ref processed).ConfigureAwait(false);
|
||||
hasMore = more.Select(r => r.Result.Page).LastOrDefault(p => p is not null)?.HasMore ?? hasMore;
|
||||
}
|
||||
|
||||
await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>Saves the posts not processed yet; returns true once known content has been met.</summary>
|
||||
private Task<bool> ProcessSweepReadsAsync(RecipeRun run, IReadOnlyList<CapturedRead> reads, ref int processed)
|
||||
{
|
||||
var items = Contents(reads);
|
||||
var fresh = items.Skip(processed).ToList();
|
||||
processed = items.Count;
|
||||
return ProcessSweepItemsAsync(run, reads, fresh);
|
||||
}
|
||||
|
||||
private async Task<bool> ProcessSweepItemsAsync(RecipeRun run, IReadOnlyList<CapturedRead> reads, IReadOnlyList<ContentItem> items)
|
||||
{
|
||||
await EnsureMineAsync(reads, run).ConfigureAwait(false);
|
||||
|
||||
// Stories bar (H2): followed accounts whose latest story is newer than their last stories check.
|
||||
foreach (var profile in reads.SelectMany(r => r.Result.Profiles).Where(p => p.LatestStoryAt is not null))
|
||||
{
|
||||
var account = await Writer.ObserveProfileAsync(profile, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
if (account is { State: not (AccountState.ArchiveOnly or AccountState.Unreachable) }
|
||||
&& account.ContentTypes.HasFlag(ContentTypes.Stories)
|
||||
&& profile.LatestStoryAt > (account.LastStoriesCheckAt ?? DateTimeOffset.MinValue))
|
||||
{
|
||||
run.AccountsWithStories.Add(account.Id);
|
||||
}
|
||||
}
|
||||
|
||||
var sawKnown = false;
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (item.Owner is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var account = await Writer.ObserveProfileAsync(item.Owner, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
if (account is null || account.State is AccountState.ArchiveOnly or AccountState.Unreachable || account.Id == 0)
|
||||
{
|
||||
continue; // not an account Febe keeps
|
||||
}
|
||||
|
||||
var saved = await Writer.SaveAsync(account, item, EntryKind.Post, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
switch (saved.Outcome)
|
||||
{
|
||||
case SaveOutcome.Created:
|
||||
run.NewEntries++;
|
||||
run.AccountsWithNewPosts.Add(account.Id);
|
||||
break;
|
||||
case SaveOutcome.Known when !item.Pinned:
|
||||
sawKnown = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return sawKnown;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Alberto's own profile («Tu») from the data the page receives (H10), the first time it is seen.
|
||||
/// </summary>
|
||||
private async Task EnsureMineAsync(IReadOnlyList<CapturedRead> reads, RecipeRun run)
|
||||
{
|
||||
if (reads.Select(r => r.Result.Viewer).FirstOrDefault(v => v is not null) is not { } viewer)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var mine = await Env.Storage.Accounts.GetMineAsync(run.Ct).ConfigureAwait(false);
|
||||
if (mine is not null || await Env.Storage.Accounts.FindByInstagramIdAsync(viewer.Id, run.Ct).ConfigureAwait(false) is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var account = Account.Create(viewer.Username, StartingPoint.EverythingAndKeepUpdated, Env.Clock.Now, Env.Clock.LocalZone, isMine: true) with
|
||||
{
|
||||
InstagramId = viewer.Id,
|
||||
};
|
||||
await Env.Storage.Accounts.AddAsync(account, run.Ct).ConfigureAwait(false);
|
||||
await Writer.EventAsync("account-collegato", $"Account collegato riconosciuto dai dati della pagina: {viewer.Username} («Tu»).", EventSeverity.Info, null, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
public sealed partial class RecipeRunner
|
||||
{
|
||||
/// <summary>
|
||||
/// Storie di un account (spec §6.3): checks that the budget allows at least ten stories, opens the viewer from the
|
||||
/// stories bar (when the home is on screen) or from the profile, watches the stories one by one with the timings of
|
||||
/// §7.7 (one StoryView permit per story shown) and saves only the stories actually shown. After the last story it
|
||||
/// closes the viewer before it moves on by itself; a story of another account is not saved: the viewer is closed
|
||||
/// and the event recorded.
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> AccountStoriesAsync(RecipeRun run)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
if (!CollectionWriter.Wants(account, EntryKind.Story))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, $"«Storie» è spento per {account.Username}.");
|
||||
}
|
||||
|
||||
await EnsureStoryBudgetAsync(run, account).ConfigureAwait(false);
|
||||
if (_lastKind == RecipeKind.AccountStories)
|
||||
{
|
||||
await Env.Driver.WaitAsync(StoryTimings.BetweenAccounts(Env.Random, Env.Driver.WaitMultiplier), run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var parameters = Values(("username", account.Username));
|
||||
var fromBar = Env.SiteMap.IsTargetConfigured(SiteTargets.HomeStory)
|
||||
&& Env.SiteMap.Match(SitePages.Home, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is not null
|
||||
&& (await run.FindAsync(SiteTargets.HomeStory, parameters).ConfigureAwait(false)).Found;
|
||||
|
||||
if (!fromBar)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => ProfileIn(r, account) is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
var profile = FindProfile(reads, account)!;
|
||||
account = await Writer.ApplyProfileAsync(account, profile, run.Ct).ConfigureAwait(false);
|
||||
if (profile.IsPrivate == true && profile.IsFollowed == false)
|
||||
{
|
||||
await MarkUnreachableAsync(run, account, UnreachableReason.PrivateNotFollowed).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"{account.Username} è un profilo privato che non segui: non si tocca.");
|
||||
}
|
||||
|
||||
if (!(await run.FindAsync(SiteTargets.ProfileStoryRing, parameters).ConfigureAwait(false)).Found)
|
||||
{
|
||||
await StoriesCheckedAsync(account, run).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed; // no active stories: nothing to open
|
||||
}
|
||||
}
|
||||
|
||||
var target = fromBar ? SiteTargets.HomeStory : SiteTargets.ProfileStoryRing;
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
var viewerMark = Env.Capture.Mark();
|
||||
var opened = await OpenViewerAsync(run, target, parameters, SitePages.StoryViewer).ConfigureAwait(false);
|
||||
var watched = await WatchViewerAsync(run, SitePages.StoryViewer, "username", account.Username, account, viewerMark, opened).ConfigureAwait(false);
|
||||
var shown = watched.Shown;
|
||||
|
||||
var stories = Contents(Env.Capture.Since(viewerMark), c => IsOwnedBy(c, account));
|
||||
foreach (var id in shown)
|
||||
{
|
||||
if (stories.FirstOrDefault(s => s.Id == id) is { } story)
|
||||
{
|
||||
var saved = await Writer.SaveAsync(account, story, EntryKind.Story, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
if (saved.Outcome == SaveOutcome.Created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await StoriesCheckedAsync(account, run).ConfigureAwait(false);
|
||||
if (watched.Stop is { } stop)
|
||||
{
|
||||
throw stop;
|
||||
}
|
||||
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raccolta in evidenza (spec §6.3): opens the profile and the collection, watches its contents one by one (one
|
||||
/// StoryView permit per content shown) and closes the viewer after the last one. A content that is a story already
|
||||
/// saved is referenced, not downloaded again (H9).
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> HighlightAsync(RecipeRun run)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
if (run.Request.HighlightId is not { Length: > 0 } highlightId)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "«Raccolta in evidenza» ha bisogno dell'identificativo della raccolta.");
|
||||
}
|
||||
|
||||
if (!CollectionWriter.Wants(account, EntryKind.Highlight))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, $"«Storie in evidenza» è spento per {account.Username}.");
|
||||
}
|
||||
|
||||
await EnsureStoryBudgetAsync(run, account).ConfigureAwait(false);
|
||||
var parameters = Values(("username", account.Username));
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Highlights.Count > 0 || ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Highlights.Count > 0 || r.Profiles.Count > 0, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
if (FindProfile(reads, account) is { } profile)
|
||||
{
|
||||
account = await Writer.ApplyProfileAsync(account, profile, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => h.Owner is null || h.Owner.Id == account.InstagramId).ToList();
|
||||
var collections = await Writer.UpsertHighlightsAsync(account, listed, run.Ct).ConfigureAwait(false);
|
||||
if (!collections.TryGetValue(highlightId, out var highlight))
|
||||
{
|
||||
var known = await Env.Storage.Highlights.FindAsync(account.Id, highlightId, run.Ct).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, known is null
|
||||
? "La raccolta non è nel profilo."
|
||||
: $"La raccolta «{known.Title}» non è più nel profilo: i suoi file restano.");
|
||||
}
|
||||
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
var viewerMark = Env.Capture.Mark();
|
||||
var opened = await OpenViewerAsync(run, SiteTargets.ProfileHighlight, Values(("id", highlightId), ("username", account.Username)), SitePages.HighlightViewer).ConfigureAwait(false);
|
||||
var watched = await WatchViewerAsync(run, SitePages.HighlightViewer, "highlight", highlightId, account, viewerMark, opened).ConfigureAwait(false);
|
||||
var shown = watched.Shown;
|
||||
|
||||
var items = Contents(Env.Capture.Since(viewerMark), c => c.HighlightId == highlightId);
|
||||
var ordered = new List<long>();
|
||||
foreach (var id in shown)
|
||||
{
|
||||
if (items.FirstOrDefault(i => i.Id == id) is not { } item)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var (entry, created) = await Writer.LinkHighlightItemAsync(account, highlight, item, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
if (created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
}
|
||||
|
||||
if (entry is not null)
|
||||
{
|
||||
ordered.Add(entry.Id);
|
||||
}
|
||||
}
|
||||
|
||||
if (items.Count > 0 && items.All(i => shown.Contains(i.Id)) && ordered.Count == items.Count)
|
||||
{
|
||||
await Env.Storage.Highlights.SetItemsAsync(highlight.Id, ordered, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Env.Storage.Highlights.UpsertAsync(highlight with { LastCheckedAt = Env.Clock.Now }, run.Ct).ConfigureAwait(false);
|
||||
if (watched.Stop is { } stop)
|
||||
{
|
||||
throw stop;
|
||||
}
|
||||
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
private async Task EnsureStoryBudgetAsync(RecipeRun run, Account account)
|
||||
{
|
||||
if (Env.Budget is { } budget)
|
||||
{
|
||||
var left = await budget.RemainingAsync(ActionKind.StoryView, account.Id, run.Ct).ConfigureAwait(false);
|
||||
if (left < Env.Options.MinStoryBudget)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Denied, $"Il tetto delle storie ne consente ancora {left}: ne servono almeno {Env.Options.MinStoryBudget} per aprirle.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Clicks what opens a viewer and waits for it; one more click if the first one went unnoticed.</summary>
|
||||
private async Task<IReadOnlyDictionary<string, string>> OpenViewerAsync(RecipeRun run, string target, IReadOnlyDictionary<string, string> parameters, string viewerPage)
|
||||
{
|
||||
for (var attempt = 0; attempt < 2; attempt++)
|
||||
{
|
||||
await run.ClickAsync(target, parameters).ConfigureAwait(false);
|
||||
if (await WaitForViewerAsync(run, viewerPage, previous: null).ConfigureAwait(false) is { } opened)
|
||||
{
|
||||
return opened;
|
||||
}
|
||||
|
||||
if (!(await run.FindAsync(target, parameters).ConfigureAwait(false)).Found)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non si è aperto dopo il clic.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Watches a viewer that shows <paramref name="opened"/>: reads the item shown from the address of the page, waits
|
||||
/// the time of §7.7, asks a StoryView permit before each «next» (and after the fact when the viewer moved on by
|
||||
/// itself) and closes the viewer after the last item of <paramref name="owner"/>, or as soon as it shows something
|
||||
/// else. On any stop other than a signal the viewer is closed first. Returns the identifiers shown, in order.
|
||||
/// </summary>
|
||||
private async Task<ViewerResult> WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, IReadOnlyDictionary<string, string> opened)
|
||||
{
|
||||
var shown = new List<string>();
|
||||
var counted = new HashSet<string>(StringComparer.Ordinal);
|
||||
var pendingPermit = true; // asked before the click that opened the viewer
|
||||
var position = opened;
|
||||
var stuck = 0;
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!string.Equals(position[ownerKey], owner, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
await Writer.EventAsync(
|
||||
"visualizzatore-altro-account",
|
||||
viewerPage == SitePages.StoryViewer
|
||||
? $"Dopo le storie di {account.Username} il visualizzatore è passato a un altro account: chiuso, quelle storie non si salvano."
|
||||
: $"Il visualizzatore è passato a un'altra raccolta di {account.Username}: chiuso senza salvarla.",
|
||||
EventSeverity.Warning,
|
||||
account.Id,
|
||||
run.Session.SessionId,
|
||||
run.Ct).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, null);
|
||||
}
|
||||
|
||||
var id = position["id"];
|
||||
if (counted.Add(id))
|
||||
{
|
||||
if (!pendingPermit)
|
||||
{
|
||||
// The viewer moved on by itself: this item was shown without asking first; ask now.
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
pendingPermit = false;
|
||||
shown.Add(id);
|
||||
}
|
||||
|
||||
// The list of the account arrives with the viewer (H4): it tells which item is the last one.
|
||||
var list = await ViewerListAsync(run, mark, viewerPage, owner, account).ConfigureAwait(false);
|
||||
var item = list.FirstOrDefault(i => i.Id == id);
|
||||
var video = item?.Files.FirstOrDefault(f => f.Kind == MediaKind.Video)?.Duration;
|
||||
await Env.Driver.WaitAsync(StoryTimings.Watch(Env.Random, video, Env.Driver.WaitMultiplier), run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return new ViewerResult(shown, null); // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!SamePosition(current, position))
|
||||
{
|
||||
position = current; // it moved on by itself while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
var index = list.FindIndex(i => i.Id == id);
|
||||
if (list.Count > 0 && index == list.Count - 1)
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, null);
|
||||
}
|
||||
|
||||
if (!pendingPermit)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
pendingPermit = true;
|
||||
}
|
||||
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
var next = await WaitForViewerAsync(run, viewerPage, previous: current).ConfigureAwait(false);
|
||||
if (next is null)
|
||||
{
|
||||
return new ViewerResult(shown, null); // closed after the last item
|
||||
}
|
||||
|
||||
if (SamePosition(next, current))
|
||||
{
|
||||
if (++stuck >= 2)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non va avanti.");
|
||||
}
|
||||
|
||||
continue; // the click went unnoticed: watch a little more and try again
|
||||
}
|
||||
|
||||
stuck = 0;
|
||||
position = next;
|
||||
}
|
||||
}
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
if (stop.Status != RecipeStatus.StoppedBySignal)
|
||||
{
|
||||
// Leave no viewer open: it would move on by itself to other accounts. After a signal the page stays as it is.
|
||||
try
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
}
|
||||
catch (RecipeStopException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return new ViewerResult(shown, stop);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a viewer showed, and why it stopped early (the caller saves what was shown, then stops).</summary>
|
||||
private sealed record ViewerResult(List<string> Shown, RecipeStopException? Stop);
|
||||
|
||||
private static bool SamePosition(IReadOnlyDictionary<string, string> a, IReadOnlyDictionary<string, string> b) =>
|
||||
a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var v) && string.Equals(v, p.Value, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>The items of the viewer for the owner, as received (waits for them the first time).</summary>
|
||||
private async Task<List<ContentItem>> ViewerListAsync(RecipeRun run, long mark, string viewerPage, string owner, Account account)
|
||||
{
|
||||
Func<ContentItem, bool> belongs = viewerPage == SitePages.StoryViewer
|
||||
? c => IsOwnedBy(c, account)
|
||||
: c => c.HighlightId == owner;
|
||||
var present = Contents(Env.Capture.Since(mark), belongs);
|
||||
if (present.Count > 0)
|
||||
{
|
||||
return present;
|
||||
}
|
||||
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Contents.Any(belongs)).ConfigureAwait(false);
|
||||
run.Judge(reads, r => r.Contents.Any(belongs), null);
|
||||
return Contents(reads, belongs);
|
||||
}
|
||||
|
||||
/// <summary>Waits until the address shows a viewer item different from <paramref name="previous"/>; null when the viewer is gone.</summary>
|
||||
private async Task<IReadOnlyDictionary<string, string>?> WaitForViewerAsync(RecipeRun run, string viewerPage, IReadOnlyDictionary<string, string>? previous)
|
||||
{
|
||||
var deadline = Env.Clock.Now + Env.Options.ViewerTimeout;
|
||||
while (true)
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
var match = Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (match is not null && (previous is null || !SamePosition(match, previous)))
|
||||
{
|
||||
return match;
|
||||
}
|
||||
|
||||
if (previous is not null && match is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Env.Clock.Now >= deadline)
|
||||
{
|
||||
return previous is null ? null : match;
|
||||
}
|
||||
|
||||
await Env.Clock.Delay(Env.Options.Poll, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Closes the viewer with its command and waits until it is gone.</summary>
|
||||
private async Task CloseViewerAsync(RecipeRun run, string viewerPage)
|
||||
{
|
||||
if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var click = await Env.Driver.ClickAsync(SiteTargets.ViewerClose, null, run.Ct).ConfigureAwait(false);
|
||||
if (!click.Found)
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
throw RecipeRun.Stop(RecipeStatus.TargetNotFound, click.Message);
|
||||
}
|
||||
|
||||
var deadline = Env.Clock.Now + Env.Options.ViewerTimeout;
|
||||
while (Env.Clock.Now < deadline)
|
||||
{
|
||||
if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await Env.Clock.Delay(Env.Options.Poll, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StoriesCheckedAsync(Account account, RecipeRun run) =>
|
||||
await Env.Storage.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { LastStoriesCheckAt = Env.Clock.Now }, run.Ct).ConfigureAwait(false);
|
||||
|
||||
private async Task MarkUnreachableAsync(RecipeRun run, Account account, UnreachableReason reason)
|
||||
{
|
||||
if (account.State == AccountState.Unreachable && account.UnreachableReason == reason)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await Env.Storage.Accounts.SetStateAsync(account.Id, AccountState.Unreachable, Env.Clock.Now, reason, run.Ct).ConfigureAwait(false);
|
||||
var why = reason switch
|
||||
{
|
||||
UnreachableReason.PrivateNotFollowed => "è un profilo privato che non segui",
|
||||
UnreachableReason.NotFound => "il profilo non esiste più",
|
||||
UnreachableReason.Renamed => "il nome ora appartiene a un altro profilo",
|
||||
_ => "non è raggiungibile",
|
||||
};
|
||||
await Writer.EventAsync("account-non-raggiungibile", $"{account.Username} non è raggiungibile: {why}.", EventSeverity.Warning, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static ProfileInfo? ProfileIn(ReadResult result, Account account) =>
|
||||
result.Profiles.FirstOrDefault(p => (account.InstagramId is { } id && p.Id == id) || string.Equals(p.Username, account.Username, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
/// <summary>Everything the recipes work with.</summary>
|
||||
public sealed record RecipeEnvironment
|
||||
{
|
||||
/// <summary>The page, through the browser (or a fake in tests and simulation).</summary>
|
||||
public required IPageDriver Driver { get; init; }
|
||||
|
||||
/// <summary>What the page receives, read by the site's readers.</summary>
|
||||
public required CaptureCollector Capture { get; init; }
|
||||
|
||||
/// <summary>The single point every counted action passes through (rule 7).</summary>
|
||||
public required IGovernor Governor { get; init; }
|
||||
|
||||
/// <summary>Stop signals: raised by the capture, reported by the recipes (empty pages, session cookie).</summary>
|
||||
public required IStopSignals Signals { get; init; }
|
||||
|
||||
public required IFebeStorage Storage { get; init; }
|
||||
|
||||
/// <summary>Pages and targets of the site (<c>bersagli.*.json</c>).</summary>
|
||||
public required SiteMap SiteMap { get; init; }
|
||||
|
||||
public required IClock Clock { get; init; }
|
||||
|
||||
public required IRandomSource Random { get; init; }
|
||||
|
||||
/// <summary>Remaining budgets (stories need at least ten). Null: the check is left to the Governor alone.</summary>
|
||||
public IBudgetView? Budget { get; init; }
|
||||
|
||||
/// <summary>Daily data budget: the backfill stops when it is used up (spec §6.3). Null: not checked here.</summary>
|
||||
public IDataBudget? DataBudget { get; init; }
|
||||
|
||||
/// <summary>The circuit breaker, to stop when it opens. Null: only the signals of the run count.</summary>
|
||||
public ICircuitBreaker? Breaker { get; init; }
|
||||
|
||||
public RecipeOptions Options { get; init; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The recipes of spec §6.3 over a page driver: Giro dei seguiti, Storie di un account, Controllo del profilo, Storico,
|
||||
/// Raccolta in evidenza, Taggati, Reel, Post singolo, Elenco dei seguiti.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Common rules: the Governor is asked before every counted action and a refusal stops the recipe in order; a stop
|
||||
/// signal stops it where it is and leaves the page as it is; a missing target stops it with a report, never with
|
||||
/// coordinates; an unknown response shape stops it with <see cref="RecipeStatus.UnrecognizedFormat"/> and an event
|
||||
/// that carries only the key structure. Recipes refuse to run on a site whose map or reader vocabulary is still a
|
||||
/// skeleton (the first Instagram files, to be filled after M0).
|
||||
/// </remarks>
|
||||
public sealed partial class RecipeRunner : IRecipeRunner
|
||||
{
|
||||
private long? _sessionId;
|
||||
private RecipeKind? _lastKind;
|
||||
|
||||
public RecipeRunner(RecipeEnvironment environment)
|
||||
{
|
||||
Env = environment ?? throw new ArgumentNullException(nameof(environment));
|
||||
Writer = new CollectionWriter(environment.Storage, environment.Clock);
|
||||
}
|
||||
|
||||
public RecipeEnvironment Env { get; }
|
||||
|
||||
public CollectionWriter Writer { get; }
|
||||
|
||||
/// <summary>Italian name of a recipe, for messages and events.</summary>
|
||||
public static string Name(RecipeKind kind) => kind switch
|
||||
{
|
||||
RecipeKind.FollowingSweep => "Giro dei seguiti",
|
||||
RecipeKind.AccountStories => "Storie di un account",
|
||||
RecipeKind.ProfileCheck => "Controllo del profilo",
|
||||
RecipeKind.Backfill => "Storico",
|
||||
RecipeKind.Highlight => "Raccolta in evidenza",
|
||||
RecipeKind.Tagged => "Taggati",
|
||||
RecipeKind.Reels => "Reel",
|
||||
RecipeKind.SinglePost => "Post singolo",
|
||||
RecipeKind.FollowingList => "Elenco dei seguiti",
|
||||
_ => kind.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>Pages and targets a recipe cannot work without.</summary>
|
||||
public static (IReadOnlyList<string> Pages, IReadOnlyList<string> Targets) Requirements(RecipeKind kind) => kind switch
|
||||
{
|
||||
RecipeKind.FollowingSweep => ([SitePages.Home], []),
|
||||
RecipeKind.AccountStories => ([SitePages.Profile, SitePages.StoryViewer], [SiteTargets.ProfileStoryRing, SiteTargets.ViewerNext, SiteTargets.ViewerClose]),
|
||||
RecipeKind.ProfileCheck or RecipeKind.Backfill => ([SitePages.Profile], [SiteTargets.ProfileNotFound]),
|
||||
RecipeKind.Highlight => ([SitePages.Profile, SitePages.HighlightViewer], [SiteTargets.ProfileHighlight, SiteTargets.ViewerNext, SiteTargets.ViewerClose]),
|
||||
RecipeKind.Tagged => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabTagged]),
|
||||
RecipeKind.Reels => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabReels]),
|
||||
RecipeKind.SinglePost => ([SitePages.Post], []),
|
||||
RecipeKind.FollowingList => ([SitePages.Following], []),
|
||||
_ => ([], []),
|
||||
};
|
||||
|
||||
/// <summary>Italian description of a stop signal.</summary>
|
||||
public static string Describe(Signal signal) => signal.Level switch
|
||||
{
|
||||
SignalLevel.Throttle => $"Segnale di rallentamento ({signal.Code}): la ricetta si ferma dov'è.",
|
||||
SignalLevel.Challenge => $"Il sito chiede una verifica ({signal.Code}): Febe si ferma e lascia la pagina com'è.",
|
||||
SignalLevel.Disconnect => $"La sessione è terminata ({signal.Code}): Febe si ferma e non tenta di rientrare.",
|
||||
_ => $"Segnale {signal.Code}.",
|
||||
};
|
||||
|
||||
public async Task<RecipeOutcome> RunAsync(RecipeRequest request, ISessionContext session, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(session);
|
||||
var name = Name(request.Kind);
|
||||
|
||||
var (pages, targets) = Requirements(request.Kind);
|
||||
var missing = Env.SiteMap.Missing(pages, targets);
|
||||
if (missing.Count > 0)
|
||||
{
|
||||
var message = $"«{name}» non può girare su {Env.SiteMap.Site}: la mappa dei bersagli non è ancora compilata (mancano {string.Join(", ", missing)}). Va completata con i campioni della sonda di M0 (ipotesi H11).";
|
||||
await Writer.EventAsync("mappa-incompleta", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
return new RecipeOutcome(RecipeStatus.TargetNotFound, 0, 0, message);
|
||||
}
|
||||
|
||||
if (Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable)
|
||||
{
|
||||
var message = $"«{name}» non può girare: {unusable}";
|
||||
await Writer.EventAsync("lettori-incompleti", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
return new RecipeOutcome(RecipeStatus.UnrecognizedFormat, 0, 0, message);
|
||||
}
|
||||
|
||||
if (Env.Breaker is { } breaker && !breaker.State.AllowsSiteActions)
|
||||
{
|
||||
return new RecipeOutcome(RecipeStatus.Denied, 0, 0, "L'interruttore è aperto: nessuna azione verso il sito.");
|
||||
}
|
||||
|
||||
if (_sessionId != session.SessionId)
|
||||
{
|
||||
Env.Driver.BeginSession(session.Mood);
|
||||
_sessionId = session.SessionId;
|
||||
_lastKind = null;
|
||||
}
|
||||
|
||||
using var run = new RecipeRun(this, request, session, ct);
|
||||
RecipeStatus status;
|
||||
string? text = null;
|
||||
try
|
||||
{
|
||||
await CheckSessionCookieAsync(run).ConfigureAwait(false);
|
||||
status = request.Kind switch
|
||||
{
|
||||
RecipeKind.FollowingSweep => await FollowingSweepAsync(run).ConfigureAwait(false),
|
||||
RecipeKind.AccountStories => await AccountStoriesAsync(run).ConfigureAwait(false),
|
||||
RecipeKind.ProfileCheck => await ProfileCheckAsync(run).ConfigureAwait(false),
|
||||
RecipeKind.Backfill => await WalkAsync(run, ProfileWalk.Posts).ConfigureAwait(false),
|
||||
RecipeKind.Tagged => await WalkAsync(run, ProfileWalk.Tagged).ConfigureAwait(false),
|
||||
RecipeKind.Reels => await WalkAsync(run, ProfileWalk.Reels).ConfigureAwait(false),
|
||||
RecipeKind.Highlight => await HighlightAsync(run).ConfigureAwait(false),
|
||||
RecipeKind.SinglePost => await SinglePostAsync(run).ConfigureAwait(false),
|
||||
RecipeKind.FollowingList => await FollowingListAsync(run).ConfigureAwait(false),
|
||||
_ => throw RecipeRun.Stop(RecipeStatus.Failed, $"Ricetta sconosciuta: {request.Kind}."),
|
||||
};
|
||||
}
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
status = stop.Status;
|
||||
text = stop.Message;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
status = RecipeStatus.Cancelled;
|
||||
text = "Ricetta interrotta.";
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
{
|
||||
// E.g. Alberto took the browser: the gesture was not performed.
|
||||
status = RecipeStatus.Cancelled;
|
||||
text = ex.Message;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
status = RecipeStatus.Failed;
|
||||
text = $"Errore imprevisto in «{name}» ({ex.GetType().Name}): {ex.Message}";
|
||||
}
|
||||
|
||||
if (run.Signal is { } signal && status is not (RecipeStatus.StoppedBySignal or RecipeStatus.Cancelled))
|
||||
{
|
||||
status = RecipeStatus.StoppedBySignal;
|
||||
text = Describe(signal);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await ReportAsync(run, status, text, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// The timeline is a convenience: failing to write it never changes how the recipe ended.
|
||||
}
|
||||
|
||||
_lastKind = request.Kind;
|
||||
return new RecipeOutcome(status, run.Actions, run.NewEntries, text)
|
||||
{
|
||||
AccountsWithStories = [.. run.AccountsWithStories],
|
||||
AccountsWithNewPosts = [.. run.AccountsWithNewPosts],
|
||||
BackfillFinished = run.Finished,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rest page (spec §6.1). After a verification request or a disconnection the page is left as it is, so that
|
||||
/// Alberto sees what happened (spec §7.6): resting is skipped while the breaker says so.
|
||||
/// </summary>
|
||||
public Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
if (Env.Breaker?.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
return Env.Driver.RestAsync(ct);
|
||||
}
|
||||
|
||||
private async Task CheckSessionCookieAsync(RecipeRun run)
|
||||
{
|
||||
if (await Env.Driver.HasSessionCookieAsync(run.Ct).ConfigureAwait(false) is false)
|
||||
{
|
||||
Env.Signals.ObserveSessionCookie(false);
|
||||
run.ThrowIfSignal();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReportAsync(RecipeRun run, RecipeStatus status, string? text, CancellationToken ct)
|
||||
{
|
||||
var name = Name(run.Request.Kind);
|
||||
var accountId = run.Request.AccountId;
|
||||
switch (status)
|
||||
{
|
||||
case RecipeStatus.UnrecognizedFormat:
|
||||
var shapes = run.UnknownShapes.Count == 0 ? "(nessuna struttura)" : string.Join(" · ", run.UnknownShapes.Take(3));
|
||||
await Writer.EventAsync("formato-non-riconosciuto", $"Formato non riconosciuto in «{name}». Struttura delle chiavi: {shapes}", EventSeverity.Warning, accountId, run.Session.SessionId, ct).ConfigureAwait(false);
|
||||
if (accountId is { } id)
|
||||
{
|
||||
await Env.Storage.Accounts.AddNoticesAsync(id, AccountNotices.UnrecognizedFormat, Env.Clock.Now, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
case RecipeStatus.TargetNotFound:
|
||||
await Writer.EventAsync("bersaglio-non-trovato", $"«{name}» si è fermata: {text}", EventSeverity.Error, accountId, run.Session.SessionId, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case RecipeStatus.Failed:
|
||||
await Writer.EventAsync("ricetta-fallita", text ?? $"«{name}» non è riuscita.", EventSeverity.Error, accountId, run.Session.SessionId, ct).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<Account> LoadAccountAsync(RecipeRun run)
|
||||
{
|
||||
if (run.Request.AccountId is not { } id)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, $"«{Name(run.Request.Kind)}» ha bisogno di un account.");
|
||||
}
|
||||
|
||||
var account = await Env.Storage.Accounts.GetAsync(id, run.Ct).ConfigureAwait(false)
|
||||
?? throw RecipeRun.Stop(RecipeStatus.Failed, $"Account {id} non trovato.");
|
||||
if (account.State == AccountState.ArchiveOnly)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Denied, $"{account.Username} è «Solo archivio»: non si contatta.");
|
||||
}
|
||||
|
||||
return account;
|
||||
}
|
||||
|
||||
/// <summary>The profile of <paramref name="account"/> in the reads: same identifier, or same name when the identifier is not known yet.</summary>
|
||||
private static ProfileInfo? FindProfile(IEnumerable<CapturedRead> reads, Account account) =>
|
||||
reads.SelectMany(r => r.Result.Profiles)
|
||||
.Where(p => account.InstagramId is { } id ? p.Id == id || string.Equals(p.Username, account.Username, StringComparison.OrdinalIgnoreCase) : string.Equals(p.Username, account.Username, StringComparison.OrdinalIgnoreCase))
|
||||
.OrderByDescending(p => (p.PostCount is null ? 0 : 1) + (p.IsPrivate is null ? 0 : 1))
|
||||
.FirstOrDefault();
|
||||
|
||||
/// <summary>Content items of the reads, in arrival order, without repetitions.</summary>
|
||||
private static List<ContentItem> Contents(IEnumerable<CapturedRead> reads, Func<ContentItem, bool>? filter = null)
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
return [.. reads.SelectMany(r => r.Result.Contents).Where(c => (filter is null || filter(c)) && seen.Add(c.Id))];
|
||||
}
|
||||
|
||||
private static bool IsOwnedBy(ContentItem item, Account account) =>
|
||||
item.Owner is { } owner && (account.InstagramId is { } id ? owner.Id == id : string.Equals(owner.Username, account.Username, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static IReadOnlyDictionary<string, string> Values(params (string Key, string Value)[] pairs) =>
|
||||
pairs.ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal);
|
||||
}
|
||||
@@ -12,7 +12,7 @@ namespace Febe.Core.Collection;
|
||||
/// The same signal code is reported at most once per <see cref="DedupeWindow"/>: a page that receives ten 429
|
||||
/// responses in a second is one throttle, not ten. Thread-safe.
|
||||
/// </remarks>
|
||||
public sealed class SignalDetector : IResponseObserver, IResponseConsumer
|
||||
public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStopSignals
|
||||
{
|
||||
private readonly SignalRules _rules;
|
||||
private readonly ICircuitBreaker _breaker;
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
/// <summary>Names of the pages of a site map (the «pages» section of <c>bersagli.*.json</c>).</summary>
|
||||
public static class SitePages
|
||||
{
|
||||
/// <summary>Home: stories bar and recent posts of followed profiles.</summary>
|
||||
public const string Home = "home";
|
||||
|
||||
/// <summary>Profile page, with {username}.</summary>
|
||||
public const string Profile = "profile";
|
||||
|
||||
/// <summary>Profile page starting after a resume point, with {username} and {cursor} (optional: backfill resume).</summary>
|
||||
public const string ProfileFrom = "profileFrom";
|
||||
|
||||
/// <summary>Reels tab of a profile resuming after {cursor} (optional).</summary>
|
||||
public const string ReelsFrom = "reelsFrom";
|
||||
|
||||
/// <summary>Tagged tab of a profile resuming after {cursor} (optional).</summary>
|
||||
public const string TaggedFrom = "taggedFrom";
|
||||
|
||||
/// <summary>Single post page, with {code}.</summary>
|
||||
public const string Post = "post";
|
||||
|
||||
/// <summary>List of the profiles Alberto follows, with {username} (Alberto's).</summary>
|
||||
public const string Following = "following";
|
||||
|
||||
/// <summary>The same list resuming after {cursor} (optional).</summary>
|
||||
public const string FollowingFrom = "followingFrom";
|
||||
|
||||
/// <summary>Shape of the address of the story viewer: {username} and {id} of the story shown.</summary>
|
||||
public const string StoryViewer = "storyViewer";
|
||||
|
||||
/// <summary>Shape of the address of the highlight viewer: {highlight} and {id} of the item shown.</summary>
|
||||
public const string HighlightViewer = "highlightViewer";
|
||||
|
||||
public static IReadOnlyList<string> All { get; } =
|
||||
[Home, Profile, ProfileFrom, ReelsFrom, TaggedFrom, Post, Following, FollowingFrom, StoryViewer, HighlightViewer];
|
||||
}
|
||||
|
||||
/// <summary>Identifiers of the targets the recipes look for (the «targets» section of <c>bersagli.*.json</c>).</summary>
|
||||
public static class SiteTargets
|
||||
{
|
||||
/// <summary>An account in the stories bar of the home, with {username}.</summary>
|
||||
public const string HomeStory = "home-story";
|
||||
|
||||
/// <summary>The profile picture with the stories ring, on a profile page, with {username}.</summary>
|
||||
public const string ProfileStoryRing = "profile-story-ring";
|
||||
|
||||
/// <summary>Read-only marker of a profile that does not exist.</summary>
|
||||
public const string ProfileNotFound = "profile-not-found";
|
||||
|
||||
public const string ProfileTabPosts = "profile-tab-posts";
|
||||
|
||||
public const string ProfileTabReels = "profile-tab-reels";
|
||||
|
||||
public const string ProfileTabTagged = "profile-tab-tagged";
|
||||
|
||||
/// <summary>A highlight collection on a profile page, with {id}.</summary>
|
||||
public const string ProfileHighlight = "profile-highlight";
|
||||
|
||||
/// <summary>The zone or command that advances the viewer to the next story.</summary>
|
||||
public const string ViewerNext = "viewer-next";
|
||||
|
||||
/// <summary>The command that closes the viewer.</summary>
|
||||
public const string ViewerClose = "viewer-close";
|
||||
|
||||
public static IReadOnlyList<string> All { get; } =
|
||||
[HomeStory, ProfileStoryRing, ProfileNotFound, ProfileTabPosts, ProfileTabReels, ProfileTabTagged, ProfileHighlight, ViewerNext, ViewerClose];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The site-specific part of a target map file that the recipes need in Core: page addresses and which targets are
|
||||
/// configured. How a target is found (role, accessible name, link shape) is the browser layer's business
|
||||
/// (<c>Febe.Browser.Targets.TargetMap</c>, same file).
|
||||
/// </summary>
|
||||
public sealed partial class SiteMap
|
||||
{
|
||||
private readonly Dictionary<string, string> _pages;
|
||||
private readonly HashSet<string> _configuredTargets;
|
||||
private readonly HashSet<string> _knownTargets;
|
||||
|
||||
public SiteMap(string site, IReadOnlyDictionary<string, string?> pages, IEnumerable<string> configuredTargets, IEnumerable<string> knownTargets, string? source = null)
|
||||
{
|
||||
Site = site;
|
||||
Source = source;
|
||||
_pages = pages.Where(p => !string.IsNullOrWhiteSpace(p.Value)).ToDictionary(p => p.Key, p => p.Value!.Trim(), StringComparer.Ordinal);
|
||||
_configuredTargets = new HashSet<string>(configuredTargets, StringComparer.Ordinal);
|
||||
_knownTargets = new HashSet<string>(knownTargets, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
public string Site { get; }
|
||||
|
||||
public string? Source { get; }
|
||||
|
||||
public bool HasPage(string name) => _pages.ContainsKey(name);
|
||||
|
||||
public bool IsTargetConfigured(string id) => _configuredTargets.Contains(id);
|
||||
|
||||
/// <summary>Pages and targets among the given ones that are still unset (Italian names for messages).</summary>
|
||||
public IReadOnlyList<string> Missing(IEnumerable<string> pages, IEnumerable<string> targets)
|
||||
{
|
||||
var missing = new List<string>();
|
||||
missing.AddRange(pages.Where(p => !HasPage(p)).Select(p => $"pagina «{p}»"));
|
||||
missing.AddRange(targets.Where(t => !IsTargetConfigured(t)).Select(t => _knownTargets.Contains(t) ? $"bersaglio «{t}» (vuoto)" : $"bersaglio «{t}» (assente)"));
|
||||
return missing;
|
||||
}
|
||||
|
||||
/// <summary>The path of page <paramref name="name"/> with its {placeholders} filled (values escaped for an address).</summary>
|
||||
/// <exception cref="InvalidOperationException">The page is not configured.</exception>
|
||||
public string BuildPath(string name, IReadOnlyDictionary<string, string>? values = null)
|
||||
{
|
||||
if (!_pages.TryGetValue(name, out var pattern))
|
||||
{
|
||||
throw new InvalidOperationException($"La pagina «{name}» non è impostata nella mappa {Source ?? Site}.");
|
||||
}
|
||||
|
||||
return Placeholder().Replace(pattern, m =>
|
||||
{
|
||||
var key = m.Groups[1].Value;
|
||||
if (values is null || !values.TryGetValue(key, out var value))
|
||||
{
|
||||
throw new InvalidOperationException($"Manca il valore di «{{{key}}}» per la pagina «{name}».");
|
||||
}
|
||||
|
||||
return Uri.EscapeDataString(value);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads an address path against the shape of page <paramref name="name"/> (e.g. the story viewer):
|
||||
/// returns the {placeholder} values, or null when the path does not have that shape.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, string>? Match(string name, string path)
|
||||
{
|
||||
if (!_pages.TryGetValue(name, out var pattern) || string.IsNullOrEmpty(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var shape = pattern.Split('?')[0];
|
||||
var names = new List<string>();
|
||||
var regex = new StringBuilder("^");
|
||||
var last = 0;
|
||||
foreach (Match m in Placeholder().Matches(shape))
|
||||
{
|
||||
regex.Append(Regex.Escape(shape[last..m.Index]));
|
||||
regex.Append("([^/]+)");
|
||||
names.Add(m.Groups[1].Value);
|
||||
last = m.Index + m.Length;
|
||||
}
|
||||
|
||||
regex.Append(Regex.Escape(shape[last..]));
|
||||
if (!shape.EndsWith('/'))
|
||||
{
|
||||
regex.Append("/?");
|
||||
}
|
||||
|
||||
regex.Append('$');
|
||||
var match = Regex.Match(path, regex.ToString(), RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(100));
|
||||
if (!match.Success)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var result = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
for (var i = 0; i < names.Count; i++)
|
||||
{
|
||||
result[names[i]] = Uri.UnescapeDataString(match.Groups[i + 1].Value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>The target map of the local test site (embedded <c>bersagli.prova.json</c>).</summary>
|
||||
public static SiteMap LoadTestSite() => LoadEmbedded("bersagli.prova.json");
|
||||
|
||||
/// <summary>The Instagram skeleton (embedded <c>bersagli.instagram.json</c>): every entry is still unset (H11).</summary>
|
||||
public static SiteMap LoadInstagram() => LoadEmbedded("bersagli.instagram.json");
|
||||
|
||||
public static SiteMap LoadOrEmbedded(string? path, string embeddedName) =>
|
||||
!string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadEmbedded(embeddedName);
|
||||
|
||||
public static SiteMap Load(string path) => Parse(File.ReadAllText(path), path);
|
||||
|
||||
/// <summary>Text of an embedded configuration file (also used by the browser layer to parse the targets).</summary>
|
||||
public static string ReadEmbeddedText(string fileName)
|
||||
{
|
||||
var resource = $"Febe.Core.Config.{fileName}";
|
||||
using var stream = typeof(SiteMap).Assembly.GetManifestResourceStream(resource)
|
||||
?? throw new FileNotFoundException($"Risorsa incorporata mancante: {resource}");
|
||||
using var reader = new StreamReader(stream);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
public static SiteMap LoadEmbedded(string fileName) => Parse(ReadEmbeddedText(fileName), fileName);
|
||||
|
||||
public static SiteMap Parse(string json, string? source = null)
|
||||
{
|
||||
var name = source ?? "bersagli";
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
document = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{name}: file non valido (riga {ex.LineNumber + 1}).", ex);
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
var root = document.RootElement;
|
||||
var site = root.TryGetProperty("site", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString()! : "sito";
|
||||
var pages = new Dictionary<string, string?>(StringComparer.Ordinal);
|
||||
if (root.TryGetProperty("pages", out var p) && p.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (var page in p.EnumerateObject())
|
||||
{
|
||||
if (!SitePages.All.Contains(page.Name, StringComparer.Ordinal))
|
||||
{
|
||||
throw new InvalidDataException($"{name}: pagina «{page.Name}» sconosciuta (ammesse: {string.Join(", ", SitePages.All)}).");
|
||||
}
|
||||
|
||||
var value = page.Value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => page.Value.GetString(),
|
||||
JsonValueKind.Object when page.Value.TryGetProperty("path", out var path) && path.ValueKind == JsonValueKind.String => path.GetString(),
|
||||
_ => null,
|
||||
};
|
||||
if (!string.IsNullOrWhiteSpace(value) && !value.StartsWith('/'))
|
||||
{
|
||||
throw new InvalidDataException($"{name}: la pagina «{page.Name}» è un percorso e comincia con «/».");
|
||||
}
|
||||
|
||||
pages[page.Name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
var configured = new List<string>();
|
||||
var known = new List<string>();
|
||||
if (root.TryGetProperty("targets", out var t) && t.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (var target in t.EnumerateObject())
|
||||
{
|
||||
known.Add(target.Name);
|
||||
if (target.Value.ValueKind == JsonValueKind.Object && IsConfigured(target.Value))
|
||||
{
|
||||
configured.Add(target.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new SiteMap(site, pages, configured, known, source);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsConfigured(JsonElement target)
|
||||
{
|
||||
foreach (var key in new[] { "role", "name", "href" })
|
||||
{
|
||||
if (target.TryGetProperty(key, out var value) && value.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(value.GetString()))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\{([A-Za-z][A-Za-z0-9_]*)\}", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Placeholder();
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"note": "SCHELETRO della prima versione (specifica §6.3, ipotesi H11). Elenca solo le pagine e i bersagli di cui le ricette hanno bisogno, tutti VUOTI: si compilano con i campioni della sonda di M0 (docs/prove-dal-vivo.md, docs/sonda/esito.md). Finché una voce necessaria è vuota, la ricetta che la usa si rifiuta di girare su Instagram e lo dice. Mai coordinate, mai nomi di classi generate: solo ruolo, nome accessibile e forma del collegamento.",
|
||||
"pages": {
|
||||
"home": { "path": "", "hypothesis": "H1", "note": "Pagina iniziale con barra delle storie e post recenti dei seguiti." },
|
||||
"profile": { "path": "", "hypothesis": "H3", "note": "Pagina di un profilo; segnaposto {username}." },
|
||||
"profileFrom": { "path": "", "hypothesis": "H3", "note": "Facoltativa: profilo che riparte da un punto di ripresa ({cursor}). Se resta vuota lo storico riprende scorrendo." },
|
||||
"reelsFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Reel." },
|
||||
"taggedFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Taggati." },
|
||||
"post": { "path": "", "hypothesis": "H3", "note": "Pagina di un post; segnaposto {code}." },
|
||||
"following": { "path": "", "hypothesis": "H11", "note": "Elenco dei profili seguiti da Alberto; segnaposto {username}." },
|
||||
"followingFrom": { "path": "", "hypothesis": "H11", "note": "Facoltativa: elenco dei seguiti da un punto di ripresa." },
|
||||
"storyViewer": { "path": "", "hypothesis": "H4", "note": "Forma dell'indirizzo del visualizzatore: {username} e {id} della storia mostrata." },
|
||||
"highlightViewer": { "path": "", "hypothesis": "H9", "note": "Forma dell'indirizzo del visualizzatore delle raccolte: {highlight} e {id}." }
|
||||
},
|
||||
"targets": {
|
||||
"home-story": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Voce della barra delle storie per un account ({username})." },
|
||||
"profile-story-ring": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Foto del profilo con l'anello delle storie." },
|
||||
"profile-not-found": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Segno, in sola lettura, di un profilo inesistente." },
|
||||
"profile-tab-posts": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Scheda dei post." },
|
||||
"profile-tab-reels": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Scheda dei reel." },
|
||||
"profile-tab-tagged": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Scheda dei post in cui l'account è taggato." },
|
||||
"profile-highlight": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Una raccolta in evidenza ({id})." },
|
||||
"viewer-next": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Zona o comando per andare alla storia successiva." },
|
||||
"viewer-close": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Comando per chiudere il visualizzatore." }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"site": "prova",
|
||||
"note": "Mappa dei bersagli del sito di prova locale (tools/Febe.SitoDiProva, specifica §14.2). Le ricette sono le stesse di Instagram: cambia solo dove trovano le cose. Ruolo, nome accessibile e forma del collegamento; mai coordinate, mai nomi di classi.",
|
||||
"pages": {
|
||||
"home": "/",
|
||||
"profile": "/profilo/{username}/",
|
||||
"profileFrom": "/profilo/{username}/?dopo={cursor}",
|
||||
"reelsFrom": "/profilo/{username}/reel/?dopo={cursor}",
|
||||
"taggedFrom": "/profilo/{username}/taggati/?dopo={cursor}",
|
||||
"post": "/post/{code}/",
|
||||
"following": "/profilo/{username}/seguiti/",
|
||||
"followingFrom": "/profilo/{username}/seguiti/?dopo={cursor}",
|
||||
"storyViewer": "/storie/{username}/{id}/",
|
||||
"highlightViewer": "/evidenza/{highlight}/{id}/"
|
||||
},
|
||||
"targets": {
|
||||
"home-story": { "role": "link", "href": "/storie/{username}/", "name": "^storie di ", "note": "Voce della barra delle storie nella pagina iniziale." },
|
||||
"profile-story-ring": { "role": "link", "href": "/storie/{username}/", "name": "^apri le storie", "note": "Foto del profilo con l'anello delle storie." },
|
||||
"profile-not-found": { "role": "heading", "name": "^profilo non trovato$" },
|
||||
"profile-tab-posts": { "role": "tab", "name": "^post$" },
|
||||
"profile-tab-reels": { "role": "tab", "name": "^reel$" },
|
||||
"profile-tab-tagged": { "role": "tab", "name": "^taggati$" },
|
||||
"profile-highlight": { "role": "link", "href": "/evidenza/{id}/" },
|
||||
"viewer-next": { "role": "button", "name": "^storia successiva$" },
|
||||
"viewer-close": { "role": "button", "name": "^chiudi$" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"status": "ipotesi",
|
||||
"note": "IPOTESI, DA CONFERMARE CON I CAMPIONI DI M0 (specifica §6.4, regola 10). Contiene solo gli indizi che la specifica stessa elenca in §6.4 (pk, code, taken_at, image_versions2.candidates, video_versions, carousel_media); ogni altro concetto è vuoto e si compila sui campioni ripuliti della sonda. Finché lo stato è «ipotesi» o manca un concetto necessario, le ricette si rifiutano di girare su Instagram.",
|
||||
"content": {
|
||||
"note": "Indizi di §6.4: chiavi viste in passato, non uno schema. Ipotesi, da confermare con i campioni di M0.",
|
||||
"id": ["pk"],
|
||||
"code": ["code"],
|
||||
"takenAt": ["taken_at"],
|
||||
"caption": [],
|
||||
"images": ["image_versions2.candidates"],
|
||||
"videos": ["video_versions"],
|
||||
"children": ["carousel_media"],
|
||||
"childCount": [],
|
||||
"owner": [],
|
||||
"pinned": [],
|
||||
"expiresAt": [],
|
||||
"duration": []
|
||||
},
|
||||
"version": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H5).",
|
||||
"url": [],
|
||||
"width": [],
|
||||
"height": [],
|
||||
"hasAudio": []
|
||||
},
|
||||
"profile": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H10).",
|
||||
"id": [],
|
||||
"username": [],
|
||||
"displayName": [],
|
||||
"isPrivate": [],
|
||||
"isFollowed": [],
|
||||
"postCount": [],
|
||||
"picture": [],
|
||||
"latestStoryAt": []
|
||||
},
|
||||
"highlight": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H9).",
|
||||
"id": [],
|
||||
"title": [],
|
||||
"owner": [],
|
||||
"items": []
|
||||
},
|
||||
"page": {
|
||||
"note": "Da compilare con i campioni di M0 (H3).",
|
||||
"hasMore": [],
|
||||
"cursor": []
|
||||
},
|
||||
"viewer": []
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"site": "prova",
|
||||
"status": "confermato",
|
||||
"note": "Vocabolario dei lettori per il sito di prova locale (tools/Febe.SitoDiProva). Il formato dei dati è sintetico, progettato per Febe e descritto in tools/Febe.SitoDiProva/LEGGIMI.md: non imita Instagram. Le date sono testi ISO 8601 in UTC.",
|
||||
"content": {
|
||||
"note": "Un contenuto: post, storia o contenuto di una raccolta. Riconosciuto quando ha numero, data e almeno una fra foto, filmati e parti.",
|
||||
"id": ["numero"],
|
||||
"code": ["sigla"],
|
||||
"takenAt": ["pubblicato"],
|
||||
"caption": ["testo"],
|
||||
"images": ["foto"],
|
||||
"videos": ["filmati"],
|
||||
"children": ["parti"],
|
||||
"childCount": ["parti_totali"],
|
||||
"owner": ["autore"],
|
||||
"pinned": ["fissato"],
|
||||
"expiresAt": ["scade"],
|
||||
"duration": ["durata"]
|
||||
},
|
||||
"version": {
|
||||
"note": "Una versione di un file: indirizzo, dimensioni e, per i filmati, se ha anche l'audio.",
|
||||
"url": ["indirizzo"],
|
||||
"width": ["larghezza"],
|
||||
"height": ["altezza"],
|
||||
"hasAudio": ["audio"]
|
||||
},
|
||||
"profile": {
|
||||
"id": ["numero"],
|
||||
"username": ["nome"],
|
||||
"displayName": ["nome_visibile"],
|
||||
"isPrivate": ["riservato"],
|
||||
"isFollowed": ["seguito"],
|
||||
"postCount": ["pubblicazioni"],
|
||||
"picture": ["ritratto"],
|
||||
"latestStoryAt": ["ultima_storia"]
|
||||
},
|
||||
"highlight": {
|
||||
"id": ["numero"],
|
||||
"title": ["titolo"],
|
||||
"owner": ["autore"],
|
||||
"items": ["contenuti"]
|
||||
},
|
||||
"page": {
|
||||
"hasMore": ["altro"],
|
||||
"cursor": ["dopo"]
|
||||
},
|
||||
"viewer": ["io"]
|
||||
}
|
||||
@@ -21,6 +21,13 @@
|
||||
"hostKinds": ["site"],
|
||||
"on": ["navigation", "document"]
|
||||
},
|
||||
{
|
||||
"code": "session-ended-url",
|
||||
"level": "disconnect",
|
||||
"path": "^/sessione-scaduta(/|$)",
|
||||
"hostKinds": ["site"],
|
||||
"on": ["navigation", "document"]
|
||||
},
|
||||
{
|
||||
"code": "wait-text",
|
||||
"level": "throttle",
|
||||
|
||||
@@ -42,6 +42,13 @@ public interface IMediaStore
|
||||
/// </summary>
|
||||
Task MarkFailedAsync(long mediaId, MediaState state, string? error, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Adds files to an existing entry at positions it does not have yet (files at positions already present are left
|
||||
/// as they are) and recomputes the state of the entry. Used by «Post singolo» to complete a series that arrived
|
||||
/// incomplete. Returns the files of the entry in position order.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<Media>> AddToEntryAsync(long entryId, IReadOnlyList<Media> media, 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);
|
||||
|
||||
|
||||
Reference in new issue
Block a user