Ricette fatte di richieste, un permesso per richiesta (#36, S3)
Otto ricette (controllo del profilo, storico, taggati, reel, storie di un account, raccolta in evidenza, post singolo, elenco dei seguiti) hanno una strada per richieste dirette accanto a quella con il browser. Ci vanno solo se ogni ruolo che servono è un'operazione configurata di richieste.<sito>.json: con Instagram nessuna lo è e Febe non costruisce il client del sito, quindi il comportamento con Instagram non cambia fino a S4. Ogni richiesta prende il suo permesso dal Governatore nella categoria di ciò che chiede (la prima pagina dei post conta come profilo); i segnali delle risposte vanno all'interruttore e fermano la ricetta prima di ogni altra richiesta. Se manca un valore o la pagina successiva, la ricetta torna alle pagine per quella volta e il motore controlla tutti e due i tetti. I tetti non cambiano: il dimezzamento delle storie viste è tolto perché toccava anche il browser e i «Su misura» salvati, e resta una domanda per Alberto prima di S4. Il simulatore ha --raccolta pagine|richieste con il costo delle operazioni separate di Instagram: sei simulazioni di 30 giorni senza superamenti. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4dcbd0b096
commit
63acae4e73
46 files changed
+3724
-136
No files matched your search
@@ -3,6 +3,7 @@ using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
@@ -36,7 +37,8 @@ public sealed class CollectionConfiguration
|
||||
CollectionConfigurationFile vocabularyFile,
|
||||
CollectionConfigurationFile mapFile,
|
||||
ReaderVocabulary? embeddedVocabulary,
|
||||
SiteMap? embeddedMap)
|
||||
SiteMap? embeddedMap,
|
||||
RequestCatalog? requests)
|
||||
{
|
||||
Site = site;
|
||||
Vocabulary = vocabulary;
|
||||
@@ -45,10 +47,17 @@ public sealed class CollectionConfiguration
|
||||
MapFile = mapFile;
|
||||
EmbeddedVocabulary = embeddedVocabulary;
|
||||
EmbeddedMap = embeddedMap;
|
||||
Blocked = BlockedBy(map, vocabulary);
|
||||
Fingerprint = FingerprintOf(site, vocabularyFile, mapFile);
|
||||
ByRequests = requests is null ? [] : RequestRoutes(requests);
|
||||
Blocked = BlockedBy(map, vocabulary, ByRequests.Select(r => r.Kind));
|
||||
Fingerprint = FingerprintOf(site, vocabularyFile, mapFile, ByRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The recipes that go by requests with the catalog given to <see cref="Describe"/> (issue #36, S3), with the names of
|
||||
/// their operations, in the order of <see cref="RecipeKind"/>; empty without a catalog.
|
||||
/// </summary>
|
||||
public IReadOnlyList<(RecipeKind Kind, IReadOnlyList<string> Operations)> ByRequests { get; }
|
||||
|
||||
/// <summary>The site name of the files (<c>instagram</c>, <c>prova</c>).</summary>
|
||||
public string Site { get; }
|
||||
|
||||
@@ -90,6 +99,7 @@ public sealed class CollectionConfiguration
|
||||
[
|
||||
$"Vocabolario dei lettori per «{Site}»: {VocabularyFile.Origin}, {vocabularyState}.",
|
||||
$"Mappa dei bersagli per «{Site}»: {MapFile.Origin}, {mapState}.",
|
||||
.. ByRequests.Select(r => $"{RecipeRunner.Name(r.Kind)}: per richieste ({string.Join(", ", r.Operations)})."),
|
||||
Blocked.Count == 0
|
||||
? "Con questa configurazione tutte le ricette possono girare."
|
||||
: $"Con questa configurazione non possono girare {Blocked.Count.ToString(CultureInfo.InvariantCulture)} ricette su {all.ToString(CultureInfo.InvariantCulture)}: {Names(Blocked)}.",
|
||||
@@ -131,8 +141,15 @@ public sealed class CollectionConfiguration
|
||||
/// as the pipeline loaded them (their <c>Source</c> tells a Data-folder copy from the embedded file). The text of a
|
||||
/// copy is read again from its path for the fingerprint.
|
||||
/// </summary>
|
||||
/// <param name="site">The site name of the files.</param>
|
||||
/// <param name="vocabulary">The reader vocabulary as loaded.</param>
|
||||
/// <param name="map">The target map as loaded.</param>
|
||||
/// <param name="requests">
|
||||
/// The catalog of the site client, when the recipes have it (issue #36, S3): the recipes it lets go by requests need
|
||||
/// only the vocabulary, and its roles are part of the fingerprint. Null: every recipe goes by the browser.
|
||||
/// </param>
|
||||
/// <exception cref="IOException">A copy in the Data folder cannot be read any more.</exception>
|
||||
public static CollectionConfiguration Describe(string site, ReaderVocabulary vocabulary, SiteMap map)
|
||||
public static CollectionConfiguration Describe(string site, ReaderVocabulary vocabulary, SiteMap map, RequestCatalog? requests = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(site);
|
||||
ArgumentNullException.ThrowIfNull(vocabulary);
|
||||
@@ -141,15 +158,40 @@ public sealed class CollectionConfiguration
|
||||
var mapFile = LoadedFile($"bersagli.{site}.json", map.Source);
|
||||
var embeddedVocabulary = vocabularyFile.IsOverride ? Try(() => ReaderVocabulary.LoadEmbedded(vocabularyFile.Name)) : vocabulary;
|
||||
var embeddedMap = mapFile.IsOverride ? Try(() => SiteMap.LoadEmbedded(mapFile.Name)) : map;
|
||||
return new CollectionConfiguration(site, vocabulary, map, vocabularyFile, mapFile, embeddedVocabulary, embeddedMap);
|
||||
return new CollectionConfiguration(site, vocabulary, map, vocabularyFile, mapFile, embeddedVocabulary, embeddedMap, requests);
|
||||
}
|
||||
|
||||
/// <summary>The recipes a map and a vocabulary do not let run, by the same rule as the runner's.</summary>
|
||||
public static IReadOnlyList<RecipeKind> BlockedBy(SiteMap map, ReaderVocabulary vocabulary)
|
||||
/// <param name="map">The target map.</param>
|
||||
/// <param name="vocabulary">The reader vocabulary.</param>
|
||||
/// <param name="byRequests">Recipes that go by requests: the map does not block them.</param>
|
||||
public static IReadOnlyList<RecipeKind> BlockedBy(SiteMap map, ReaderVocabulary vocabulary, IEnumerable<RecipeKind>? byRequests = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(map);
|
||||
ArgumentNullException.ThrowIfNull(vocabulary);
|
||||
return vocabulary.IsUsable ? MissingFrom(map) : Enum.GetValues<RecipeKind>();
|
||||
if (!vocabulary.IsUsable)
|
||||
{
|
||||
return Enum.GetValues<RecipeKind>();
|
||||
}
|
||||
|
||||
var routed = byRequests?.ToHashSet() ?? [];
|
||||
return [.. MissingFrom(map).Where(kind => !routed.Contains(kind))];
|
||||
}
|
||||
|
||||
/// <summary>The recipes <paramref name="catalog"/> lets go by requests, with the names of their operations.</summary>
|
||||
public static IReadOnlyList<(RecipeKind Kind, IReadOnlyList<string> Operations)> RequestRoutes(RequestCatalog catalog)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(catalog);
|
||||
var routes = new List<(RecipeKind, IReadOnlyList<string>)>();
|
||||
foreach (var kind in Enum.GetValues<RecipeKind>())
|
||||
{
|
||||
if (kind != RecipeKind.FollowingSweep && RecipeRunner.RequestOperations(catalog, kind) is { } operations)
|
||||
{
|
||||
routes.Add((kind, [.. operations.Select(o => o.Name)]));
|
||||
}
|
||||
}
|
||||
|
||||
return routes;
|
||||
}
|
||||
|
||||
/// <summary>The recipes whose pages or targets the map lacks, whatever the vocabulary.</summary>
|
||||
@@ -183,10 +225,17 @@ public sealed class CollectionConfiguration
|
||||
}
|
||||
}
|
||||
|
||||
private static string FingerprintOf(string site, CollectionConfigurationFile vocabulary, CollectionConfigurationFile map)
|
||||
private static string FingerprintOf(string site, CollectionConfigurationFile vocabulary, CollectionConfigurationFile map, IReadOnlyList<(RecipeKind Kind, IReadOnlyList<string> Operations)> byRequests)
|
||||
{
|
||||
static string Normalized(string text) => text.Replace("\r\n", "\n", StringComparison.Ordinal);
|
||||
var routes = byRequests.Select(r => $"{r.Kind}={string.Join(',', r.Operations)}");
|
||||
var text = string.Join('\n', site, vocabulary.Name, Normalized(vocabulary.Text), map.Name, Normalized(map.Text));
|
||||
|
||||
// The routes by requests change what runs: a new role clears the suspensions too. None: the fingerprint of S2.
|
||||
if (byRequests.Count > 0)
|
||||
{
|
||||
text += "\nrichieste\n" + string.Join('\n', routes);
|
||||
}
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
|
||||
}
|
||||
|
||||
|
||||
@@ -19,4 +19,11 @@ public interface IStopSignals
|
||||
|
||||
/// <summary>Result of the session-cookie check: a missing cookie is a disconnection.</summary>
|
||||
Signal? ObserveSessionCookie(bool present);
|
||||
|
||||
/// <summary>
|
||||
/// A signal read elsewhere, from an answer of the site client (<see cref="Requests.SiteAnswerSignals"/>, issue #36):
|
||||
/// it goes to the circuit breaker through the same detector, with the same deduplication, as the captured ones.
|
||||
/// Returns the signal when it was reported, null when the same code was reported within the deduplication window.
|
||||
/// </summary>
|
||||
Signal? Report(Signal signal);
|
||||
}
|
||||
@@ -41,6 +41,56 @@ public sealed record RecipeOptions
|
||||
|
||||
/// <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>
|
||||
/// Controllo del profilo by requests: the tray of the highlight collections, when it is an operation of its own, is
|
||||
/// asked at most once in this time per account (a manual check always asks).
|
||||
/// </summary>
|
||||
public TimeSpan HighlightsTrayInterval { get; init; } = DefaultHighlightsTrayInterval;
|
||||
|
||||
/// <summary>The default of <see cref="HighlightsTrayInterval"/> (also the simulator's).</summary>
|
||||
public static readonly TimeSpan DefaultHighlightsTrayInterval = TimeSpan.FromHours(24);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The waits between the requests of one recipe (issue #36, S3), for the «naturale» pace: 1–6 s (median 2.2 s) after
|
||||
/// an answer before the next request, 2–8 s (median 3.5 s) between two pages of a walk, and on any of them an 8% chance
|
||||
/// of a longer pause of 15–90 s. Every value is multiplied by mood and pace. They come on top of the Governor's minimum
|
||||
/// spacing (§7.7), never in its place.
|
||||
/// </summary>
|
||||
public static class RequestTimings
|
||||
{
|
||||
public static readonly TimeSpan AfterAnswerMin = TimeSpan.FromSeconds(1);
|
||||
public static readonly TimeSpan AfterAnswerMax = TimeSpan.FromSeconds(6);
|
||||
public static readonly TimeSpan AfterAnswerMedian = TimeSpan.FromSeconds(2.2);
|
||||
public static readonly TimeSpan BetweenPagesMin = TimeSpan.FromSeconds(2);
|
||||
public static readonly TimeSpan BetweenPagesMax = TimeSpan.FromSeconds(8);
|
||||
public static readonly TimeSpan BetweenPagesMedian = TimeSpan.FromSeconds(3.5);
|
||||
public static readonly TimeSpan LongPauseMin = TimeSpan.FromSeconds(15);
|
||||
public static readonly TimeSpan LongPauseMax = TimeSpan.FromSeconds(90);
|
||||
|
||||
/// <summary>The chance of a longer pause on a gap.</summary>
|
||||
public const double LongPauseChance = 0.08;
|
||||
|
||||
/// <summary>The wait after an answer, before the next request of the same run.</summary>
|
||||
public static TimeSpan AfterAnswer(IRandomSource random, double multiplier) =>
|
||||
Gap(random, AfterAnswerMin, AfterAnswerMax, AfterAnswerMedian, multiplier);
|
||||
|
||||
/// <summary>The wait between two pages of a walk.</summary>
|
||||
public static TimeSpan BetweenPages(IRandomSource random, double multiplier) =>
|
||||
Gap(random, BetweenPagesMin, BetweenPagesMax, BetweenPagesMedian, multiplier);
|
||||
|
||||
private static TimeSpan Gap(IRandomSource random, TimeSpan min, TimeSpan max, TimeSpan median, double multiplier)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(random);
|
||||
var wait = random.Between(min, max, median);
|
||||
if (random.Chance(LongPauseChance))
|
||||
{
|
||||
wait += random.Between(LongPauseMin, LongPauseMax);
|
||||
}
|
||||
|
||||
return TimeSpan.FromTicks((long)(wait.Ticks * multiplier));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Pacing;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
/// <summary>Which wait of <see cref="RequestTimings"/> comes before a request.</summary>
|
||||
internal enum RequestGap
|
||||
{
|
||||
/// <summary>The first request of the run: none.</summary>
|
||||
None,
|
||||
|
||||
/// <summary>After an answer, before the next request of the same run.</summary>
|
||||
AfterAnswer,
|
||||
|
||||
/// <summary>Between two pages of a walk.</summary>
|
||||
BetweenPages,
|
||||
}
|
||||
|
||||
/// <summary>What one request of a run gave: the reads of its answer, or a «not found» of the site (a 404 with JSON).</summary>
|
||||
/// <param name="Operation">The operation asked.</param>
|
||||
/// <param name="Reads">What the readers made of the answer (empty for a «not found»).</param>
|
||||
/// <param name="NotFound">The site said the resource is not there (H19): counted as an empty page, the recipe decides.</param>
|
||||
internal sealed record RequestReply(SiteOperation Operation, IReadOnlyList<CapturedRead> Reads, bool NotFound);
|
||||
|
||||
internal sealed partial class RecipeRun
|
||||
{
|
||||
/// <summary>The requests of the site client this run made (each under its own permit).</summary>
|
||||
public int RequestsAsked { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// One request of the site client in this run (issue #36, S3): the wait of <paramref name="gap"/>, then the permit
|
||||
/// of the Governor in the category of the request (<see cref="SiteOperation.CategoryFor"/>), then the request with
|
||||
/// that very permit, never another (rule 8). A refusal of the Governor stops the run in order as for a page. The
|
||||
/// answer is read for the stop signals of §7.6 first (<see cref="SiteAnswerSignals"/>): a signal goes to the
|
||||
/// detector and the circuit breaker and stops the run where it is, before any other request. A 404 with JSON is an
|
||||
/// empty page and a «not found» for the recipe; a 5xx with JSON, an answer that never came or broke, an empty page
|
||||
/// and a failure of the run, never tried again in it (H19). Otherwise the body goes to the readers, only to them,
|
||||
/// and the reads of that answer come back. The diagnostics see the request as a page fetch: the shape of the path
|
||||
/// and the status, never a value (rule 10). With <paramref name="notFoundIsEmpty"/> false a 404 is not counted as an
|
||||
/// empty page: the recipe explains it itself (the stories of an account, whose «not found» may be a private
|
||||
/// profile or no stories at all).
|
||||
/// </summary>
|
||||
public async Task<RequestReply> AskAsync(SiteOperation operation, SiteRequest request, long? accountId, RequestGap gap, bool notFoundIsEmpty = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operation);
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var requests = Env.Requests ?? throw new InvalidOperationException("Il client del sito non è configurato per le ricette.");
|
||||
ThrowIfSignal();
|
||||
|
||||
// The first request of a run waits nothing here: the engine has spaced the runs already.
|
||||
if (gap != RequestGap.None && RequestsAsked > 0)
|
||||
{
|
||||
var multiplier = Session.Mood * GesturePaceFactors.For(requests.Pace);
|
||||
var wait = gap == RequestGap.BetweenPages
|
||||
? RequestTimings.BetweenPages(Env.Random, multiplier)
|
||||
: RequestTimings.AfterAnswer(Env.Random, multiplier);
|
||||
await Env.Clock.Delay(wait, Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var permit = await PermitAsync(operation.CategoryFor(request), accountId, opensPage: true).ConfigureAwait(false);
|
||||
RequestsAsked++;
|
||||
SiteAnswer answer;
|
||||
try
|
||||
{
|
||||
answer = await requests.Requester.SendAsync(request, permit, Ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (SiteSessionMissingException missing)
|
||||
{
|
||||
// No saved session, or one without what the catalog asks: a disconnection, never a way back to the pages
|
||||
// (rule 7: the browser and the site client never use the session together).
|
||||
var stop = SiteAnswerSignals.ForMissingSession(missing, Env.Clock.Now);
|
||||
_signals.Report(stop.Signal);
|
||||
throw Stop(RecipeStatus.StoppedBySignal, stop.Message);
|
||||
}
|
||||
catch (SiteUnreachableException unreachable)
|
||||
{
|
||||
Env.Signals.ObserveEmptyPage(operation.PathShape);
|
||||
ThrowIfSignal();
|
||||
throw Stop(RecipeStatus.Failed, $"Il sito non ha risposto a «{operation.Name}» ({Why(unreachable.Reason)}): si riprova al prossimo giro.");
|
||||
}
|
||||
catch (SiteRequestRefusedException refused)
|
||||
{
|
||||
// Refused before leaving (a stale catalog, or a bug of Febe): nothing reached the site.
|
||||
requests.Warn?.Invoke($"Client del sito: richiesta «{operation.Name}» rifiutata prima di partire.");
|
||||
throw new RecipeStopException(RecipeStatus.Failed, refused.Message) { ErrorType = refused.GetType().Name };
|
||||
}
|
||||
|
||||
var descriptor = new ResponseDescriptor(
|
||||
"richiesta-" + _runner.NextRequestNumber().ToString(CultureInfo.InvariantCulture),
|
||||
HostKind.Site,
|
||||
operation.PathShape,
|
||||
string.Empty,
|
||||
operation.PathShape,
|
||||
answer.Status,
|
||||
answer.MimeType,
|
||||
"Fetch",
|
||||
false,
|
||||
Env.Clock.Now);
|
||||
Env.Diagnostics?.OnResponse(descriptor);
|
||||
Env.Diagnostics?.OnLoadingFinished(descriptor.RequestId, answer.Body.Length);
|
||||
|
||||
if (requests.AnswerSignals.Classify(operation, answer, Env.Clock.Now) is { } signal)
|
||||
{
|
||||
Env.Diagnostics?.OnBodyDropped(descriptor.RequestId, BodyDropReason.NoConsumers);
|
||||
_signals.Report(signal.Signal);
|
||||
throw Stop(RecipeStatus.StoppedBySignal, signal.Hypothesis is { } hypothesis ? $"{signal.Message} (ipotesi {hypothesis})" : signal.Message);
|
||||
}
|
||||
|
||||
if (answer.Status == 404)
|
||||
{
|
||||
Env.Diagnostics?.OnBodyDropped(descriptor.RequestId, BodyDropReason.NoConsumers);
|
||||
if (notFoundIsEmpty)
|
||||
{
|
||||
Env.Signals.ObserveEmptyPage(operation.PathShape);
|
||||
ThrowIfSignal();
|
||||
}
|
||||
|
||||
return new RequestReply(operation, [], NotFound: true);
|
||||
}
|
||||
|
||||
if (answer.Status >= 500)
|
||||
{
|
||||
Env.Diagnostics?.OnBodyDropped(descriptor.RequestId, BodyDropReason.NoConsumers);
|
||||
Env.Signals.ObserveEmptyPage(operation.PathShape);
|
||||
ThrowIfSignal();
|
||||
throw Stop(RecipeStatus.Failed, $"Il sito ha risposto con un errore ({answer.Status.ToString(CultureInfo.InvariantCulture)}) a «{operation.Name}»: si riprova al prossimo giro.");
|
||||
}
|
||||
|
||||
var mark = Env.Capture.Mark();
|
||||
await _runner.Delivery.DeliverBodyAsync(descriptor, answer.Body, [Env.Capture], Ct).ConfigureAwait(false);
|
||||
var reads = Env.Capture.Since(mark).Where(r => string.Equals(r.Response.RequestId, descriptor.RequestId, StringComparison.Ordinal)).ToList();
|
||||
ThrowIfSignal();
|
||||
return new RequestReply(operation, reads, NotFound: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An answer the readers recognized, whose content the recipe does not judge (the stories of an account: none is a
|
||||
/// quiet day): the site gives data, so the count of empty pages in a row starts again.
|
||||
/// </summary>
|
||||
public void SawData() => _signals.ObserveNonEmptyPage();
|
||||
|
||||
private static string Why(SiteUnreachableReason reason) => reason switch
|
||||
{
|
||||
SiteUnreachableReason.Timeout => "nessuna risposta in tempo",
|
||||
SiteUnreachableReason.TooLarge => "risposta troppo grande",
|
||||
SiteUnreachableReason.Broken => "risposta rovinata",
|
||||
_ => "collegamento non riuscito",
|
||||
};
|
||||
}
|
||||
@@ -20,7 +20,7 @@ internal sealed class RecipeStopException(RecipeStatus status, string message) :
|
||||
/// 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
|
||||
internal sealed partial class RecipeRun : IDisposable
|
||||
{
|
||||
private readonly RecipeRunner _runner;
|
||||
private readonly IStopSignals _signals;
|
||||
@@ -81,9 +81,10 @@ internal sealed class RecipeRun : IDisposable
|
||||
/// <summary>
|
||||
/// Asks the Governor for a counted action; stops in order when refused or when the session is over. With
|
||||
/// <paramref name="opensPage"/> (the next step opens a page), this is a turn point of the page (issue #37): when the
|
||||
/// profile search waits, it gets the page for one step first, and the checks run again after it.
|
||||
/// profile search waits, it gets the page for one step first, and the checks run again after it. Returns the
|
||||
/// permit granted: a request of the site client goes with that very permit (one per request, rule 8).
|
||||
/// </summary>
|
||||
public async Task PermitAsync(ActionKind kind, long? accountId, bool opensPage = false)
|
||||
public async Task<Permit> PermitAsync(ActionKind kind, long? accountId, bool opensPage = false)
|
||||
{
|
||||
ThrowIfSignal();
|
||||
if (opensPage && Env.PageTurns is { } turns && turns.EngineTurn is { } turn && await turns.YieldAsync(turn, Ct).ConfigureAwait(false))
|
||||
@@ -104,6 +105,7 @@ internal sealed class RecipeRun : IDisposable
|
||||
}
|
||||
|
||||
Actions++;
|
||||
return permit;
|
||||
}
|
||||
|
||||
/// <summary>Opens a page of the site map and waits after the load like a person (§7.7).</summary>
|
||||
|
||||
@@ -22,6 +22,37 @@ public sealed partial class RecipeRunner
|
||||
/// 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)
|
||||
{
|
||||
var (entry, account) = await LoadPostEntryAsync(run, needsCode: true).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.SinglePost, account.Id, opensPage: true).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, PostNotFoundMessage);
|
||||
}
|
||||
|
||||
return await CompletePostAsync(run, entry, account, Contents(reads, Matches).First()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Completes the entry with the post just read, whatever brought it, and ends the run with what changed.</summary>
|
||||
private async Task<RecipeStatus> CompletePostAsync(RecipeRun run, Entry entry, Account account, Readers.ContentItem item)
|
||||
{
|
||||
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>Outcome message of a post page (or answer) that did not give the post.</summary>
|
||||
private const string PostNotFoundMessage = "La pagina del post non ha dato il post: forse non esiste più.";
|
||||
|
||||
/// <summary>
|
||||
/// The entry a «Post singolo» completes and its account: it must exist, be a post (never a story, a collection item
|
||||
/// or a profile picture), not be deleted, and — with <paramref name="needsCode"/> — have its code; its account must
|
||||
/// not be «Solo archivio». Stops the run otherwise.
|
||||
/// </summary>
|
||||
private async Task<(Entry Entry, Account Account)> LoadPostEntryAsync(RecipeRun run, bool needsCode)
|
||||
{
|
||||
if (run.Request.EntryId is not { } entryId)
|
||||
{
|
||||
@@ -35,9 +66,9 @@ public sealed partial class RecipeRunner
|
||||
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)
|
||||
if (entry.State == EntryState.Deleted || (needsCode && 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.");
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, needsCode && 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)
|
||||
@@ -47,19 +78,7 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.Denied, $"{account.Username} è «Solo archivio»: non si contatta.");
|
||||
}
|
||||
|
||||
await run.PermitAsync(ActionKind.SinglePost, account.Id, opensPage: true).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.");
|
||||
return (entry, account);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -157,9 +176,20 @@ public sealed partial class RecipeRunner
|
||||
read = Math.Max(read, readBefore); // not back there yet: the stored point stays
|
||||
}
|
||||
|
||||
return await FinishFollowingAsync(run, finished, read, started!.Value, cursor).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The end of a run of the following list, whatever turned its pages: at the end of the list the profiles not read
|
||||
/// since it started are removed and the progress cleared («seguiti-letti»); otherwise the progress is stored for the
|
||||
/// next session («seguiti-parziale»). Always ends the run.
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> FinishFollowingAsync(RecipeRun run, bool finished, int read, DateTimeOffset started, string? cursor)
|
||||
{
|
||||
var settings = Env.Storage.Settings;
|
||||
if (finished)
|
||||
{
|
||||
var removed = await Env.Storage.Following.RemoveNotReadSinceAsync(started!.Value, run.Ct).ConfigureAwait(false);
|
||||
var removed = await Env.Storage.Following.RemoveNotReadSinceAsync(started, run.Ct).ConfigureAwait(false);
|
||||
await settings.SetManyAsync(
|
||||
new Dictionary<string, string?> { [FollowingKeys.Cursor] = null, [FollowingKeys.StartedAt] = null, [FollowingKeys.Read] = null },
|
||||
run.Ct).ConfigureAwait(false);
|
||||
@@ -173,7 +203,7 @@ public sealed partial class RecipeRunner
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
[FollowingKeys.Cursor] = cursor,
|
||||
[FollowingKeys.StartedAt] = started!.Value.ToString("O", CultureInfo.InvariantCulture),
|
||||
[FollowingKeys.StartedAt] = started.ToString("O", CultureInfo.InvariantCulture),
|
||||
[FollowingKeys.Read] = read.ToString(CultureInfo.InvariantCulture),
|
||||
},
|
||||
run.Ct).ConfigureAwait(false);
|
||||
|
||||
@@ -95,6 +95,9 @@ public sealed partial class RecipeRunner
|
||||
|
||||
/// <summary>No page came after the bursts (counted as an empty page).</summary>
|
||||
NoData,
|
||||
|
||||
/// <summary>By requests: the pages go on, but there is no request for the next one (no cursor, or its role not configured).</summary>
|
||||
NoNext,
|
||||
}
|
||||
|
||||
/// <summary>The rules of one walk over the pages of a profile, starting from the page on screen.</summary>
|
||||
@@ -143,22 +146,55 @@ public sealed partial class RecipeRunner
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
var (current, reads) = await OpenProfileAsync(run, account, waitForGrid: true).ConfigureAwait(false);
|
||||
account = current;
|
||||
var profile = AccountProfile(reads, account)!;
|
||||
await RecordCheckedProfileAsync(run, account, AccountProfile(reads, account)!, reads, highlights: true).ConfigureAwait(false);
|
||||
var (items, tailIsNew, fillGap) = await SaveFirstGridPageAsync(run, account, reads).ConfigureAwait(false);
|
||||
if (fillGap)
|
||||
{
|
||||
await FillGapAsync(run, account, reads, items, tailIsNew).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a profile check keeps of the profile, whatever brought it: whether it has stories newer than the last
|
||||
/// look, the list of its highlight collections (when <paramref name="highlights"/>: the list was read), a copy of
|
||||
/// its picture when it changed.
|
||||
/// </summary>
|
||||
private async Task RecordCheckedProfileAsync(RecipeRun run, Account account, ProfileInfo profile, IReadOnlyList<CapturedRead> reads, bool highlights)
|
||||
{
|
||||
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 (highlights)
|
||||
{
|
||||
await UpsertListedHighlightsAsync(run, account, reads).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if ((await Writer.SaveProfilePictureAsync(account, profile, run.Ct).ConfigureAwait(false)).Outcome == SaveOutcome.Created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The highlight collections of the account that <paramref name="reads"/> list, stored.</summary>
|
||||
private Task UpsertListedHighlightsAsync(RecipeRun run, Account account, IReadOnlyList<CapturedRead> reads)
|
||||
{
|
||||
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => h.Owner is null || h.Owner.Id == account.InstagramId).ToList();
|
||||
return Writer.UpsertHighlightsAsync(account, listed, run.Ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the first page of the grid of a profile check, whatever brought it, and starts or ends the history when
|
||||
/// it has not started yet. Returns the items of the page, whether the last regular one was new, and whether the
|
||||
/// gap below the page is to be filled (the history has started or ended: <see cref="FillGapAsync"/>).
|
||||
/// </summary>
|
||||
private async Task<(IReadOnlyList<ContentItem> Items, bool TailIsNew, bool FillGap)> SaveFirstGridPageAsync(RecipeRun run, Account account, IReadOnlyList<CapturedRead> reads)
|
||||
{
|
||||
// The whole first page is read (it is on screen already): known posts at its top do not hide new ones below
|
||||
// them, e.g. when the giro dei seguiti saved only the newest. Pinned posts are known but stop nothing.
|
||||
var walk = ProfileWalk.Posts;
|
||||
@@ -197,14 +233,12 @@ public sealed partial class RecipeRunner
|
||||
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
|
||||
run.Finished = account.State == AccountState.Backfilling;
|
||||
}
|
||||
}
|
||||
else if (CollectionWriter.Wants(account, EntryKind.Post) && (account.BackfillCursor is not null || account.BackfillCompletedAt is not null))
|
||||
{
|
||||
await FillGapAsync(run, account, reads, items, tailIsNew: tail == SaveOutcome.Created).ConfigureAwait(false);
|
||||
|
||||
return (items, tail == SaveOutcome.Created, false);
|
||||
}
|
||||
|
||||
await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed;
|
||||
var fillGap = CollectionWriter.Wants(account, EntryKind.Post) && (account.BackfillCursor is not null || account.BackfillCompletedAt is not null);
|
||||
return (items, tail == SaveOutcome.Created, fillGap);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -313,37 +347,14 @@ public sealed partial class RecipeRunner
|
||||
private async Task<RecipeStatus> WalkAsync(RecipeRun run, ProfileWalk walk)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
if (!CollectionWriter.Wants(account, walk.Kind))
|
||||
if (await WalkStartAsync(run, account, walk).ConfigureAwait(false) is not { } start)
|
||||
{
|
||||
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}.");
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
var (cursor, checkOnly) = start;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
var target = cursor is null ? null : ResumePoint.Parse(cursor, await settings.GetAsync(walk.MarkKey(account.Id), run.Ct).ConfigureAwait(false));
|
||||
if (!checkOnly)
|
||||
{
|
||||
@@ -406,6 +417,18 @@ public sealed partial class RecipeRunner
|
||||
Store = (next, last) => StoreWalkPointAsync(run, account, walk, next, last),
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
await FinishWalkAsync(run, account, walk, end, checkOnly, caughtUp, catchUpPages).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The end of a walk of Storico, Taggati or Reel, whatever turned its pages: at the beginning of the profile, or a
|
||||
/// history limit (not on a check-only walk), the walk is complete and its point cleared; when the stored point was
|
||||
/// not found again by scrolling, the timeline says so and the point stays.
|
||||
/// </summary>
|
||||
private async Task FinishWalkAsync(RecipeRun run, Account account, ProfileWalk walk, WalkEnd end, bool checkOnly, bool caughtUp, int catchUpPages)
|
||||
{
|
||||
var settings = Env.Storage.Settings;
|
||||
if (end == WalkEnd.EndOfList || (end == WalkEnd.Limit && !checkOnly))
|
||||
{
|
||||
run.Finished = true;
|
||||
@@ -438,8 +461,6 @@ public sealed partial class RecipeRunner
|
||||
run.Session.SessionId,
|
||||
run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -754,7 +775,23 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
var profile = AccountProfile(reads, account)!;
|
||||
account = await ApplyProfileStateAsync(run, account, AccountProfile(reads, account)!).ConfigureAwait(false);
|
||||
if (waitForGrid)
|
||||
{
|
||||
reads = await WaitForGridAsync(run, mark, account, reads).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return (account, reads);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the profile just read says of the account, whatever brought it (the page or a request): a name now used by
|
||||
/// another account, private profile not followed (rule 6: not touched; both stop the run as
|
||||
/// <see cref="RecipeStatus.AccountUnreachable"/>), the facts of the profile, an unreachable account reachable again.
|
||||
/// Returns the updated account.
|
||||
/// </summary>
|
||||
private async Task<Account> ApplyProfileStateAsync(RecipeRun run, Account account, ProfileInfo profile)
|
||||
{
|
||||
if (account.InstagramId is { } known && profile.Id != known)
|
||||
{
|
||||
await MarkUnreachableAsync(run, account, UnreachableReason.Renamed).ConfigureAwait(false);
|
||||
@@ -776,12 +813,7 @@ public sealed partial class RecipeRunner
|
||||
account = await Env.Storage.Accounts.GetAsync(account.Id, run.Ct).ConfigureAwait(false) ?? account;
|
||||
}
|
||||
|
||||
if (waitForGrid)
|
||||
{
|
||||
reads = await WaitForGridAsync(run, mark, account, reads).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return (account, reads);
|
||||
return account;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
public sealed partial class RecipeRunner
|
||||
{
|
||||
/// <summary>
|
||||
/// Post singolo by requests (spec §6.3, §6.5 point 5): one request (one SinglePost) for the post, by its code or its
|
||||
/// identifier as the operation asks. A «not found» or an answer without the post ends the run as by the page.
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> SinglePostByRequestsAsync(RecipeRun run)
|
||||
{
|
||||
var operation = Catalog.ForRole(RequestRole.Post)!;
|
||||
var (entry, account) = await LoadPostEntryAsync(run, needsCode: operation.RequiredValues.Contains(CaseValues.Code)).ConfigureAwait(false);
|
||||
var values = AccountValues(account);
|
||||
Put(values, CaseValues.Code, entry.Code);
|
||||
Put(values, CaseValues.MediaId, entry.InstagramId);
|
||||
var reply = await AskAsync(run, operation, values, null, account.Id, RequestGap.None).ConfigureAwait(false);
|
||||
if (reply.NotFound)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, PostNotFoundMessage);
|
||||
}
|
||||
|
||||
bool Matches(ContentItem c) => c.Id == entry.InstagramId || (c.Code is not null && c.Code == entry.Code);
|
||||
if (!run.Judge(reply.Reads, r => r.Contents.Any(Matches), operation.PathShape))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, PostNotFoundMessage);
|
||||
}
|
||||
|
||||
return await CompletePostAsync(run, entry, account, Contents(reply.Reads, Matches).First()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Elenco dei seguiti by requests (spec §4.2, §6.3): the first page, or the page after the stored cursor, then one
|
||||
/// request per page (one FollowingListPage each) until the end of the list or the pages of the run; the progress is
|
||||
/// stored as by the page (<see cref="FinishFollowingAsync"/>). The stored point is asked for directly, never found
|
||||
/// again by reading the list from the top.
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> FollowingListByRequestsAsync(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 = ParseTime(await settings.GetAsync(FollowingKeys.StartedAt, run.Ct).ConfigureAwait(false));
|
||||
var read = (int)(await settings.GetInt64Async(FollowingKeys.Read, run.Ct).ConfigureAwait(false) ?? 0);
|
||||
var stored = cursor is not null && started is not null ? cursor : null;
|
||||
var first = Catalog.ForRole(RequestRole.Following)!;
|
||||
var next = Catalog.ForRole(RequestRole.FollowingNext);
|
||||
if (stored is null)
|
||||
{
|
||||
cursor = null;
|
||||
read = 0;
|
||||
started = Env.Clock.Now;
|
||||
}
|
||||
else if (next is null)
|
||||
{
|
||||
await NextPagesNotConfiguredAsync(run, null).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, $"Letti {ItalianText.Number(read)} profili: le pagine successive non sono ancora configurate per le richieste.");
|
||||
}
|
||||
|
||||
var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.FollowingPagesPerRun);
|
||||
var values = AccountValues(mine);
|
||||
bool Listed(ReadResult r) => r.Profiles.Any(p => IsListed(p, mine));
|
||||
var reply = stored is null
|
||||
? await AskAsync(run, first, values, null, mine.Id, RequestGap.None).ConfigureAwait(false)
|
||||
: await AskAsync(run, next!, values, stored, mine.Id, RequestGap.None).ConfigureAwait(false);
|
||||
var pages = 1;
|
||||
var finished = false;
|
||||
while (true)
|
||||
{
|
||||
if (reply.NotFound || !run.Judge(reply.Reads, Listed, null))
|
||||
{
|
||||
if (pages == 1)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
read += await SaveFollowingPageAsync(run, reply.Reads, mine, read).ConfigureAwait(false);
|
||||
var page = PageOf(reply.Reads, r => r.Profiles.Where(p => IsListed(p, mine)).Select(p => p.Id), r => r.Shape == ReadShape.Empty);
|
||||
cursor = page?.Cursor ?? cursor;
|
||||
if (page?.HasMore == false)
|
||||
{
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (pages >= maxPages)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (next is null || page?.Cursor is not { } following)
|
||||
{
|
||||
if (next is null)
|
||||
{
|
||||
await NextPagesNotConfiguredAsync(run, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
reply = await AskAsync(run, next, values, following, mine.Id, RequestGap.BetweenPages).ConfigureAwait(false);
|
||||
pages++;
|
||||
}
|
||||
|
||||
return await FinishFollowingAsync(run, finished, read, started!.Value, cursor).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
public sealed partial class RecipeRunner
|
||||
{
|
||||
/// <summary>The last time the list of highlight collections of an account was asked by requests.</summary>
|
||||
private static string HighlightsTrayKey(long accountId) => $"raccolte.vassoio.{accountId.ToString(CultureInfo.InvariantCulture)}";
|
||||
|
||||
/// <summary>
|
||||
/// Controllo del profilo by requests (spec §6.3): the profile (one ProfileOpen), the first page of posts and the
|
||||
/// list of collections, each asked only when another operation carries it (the test site gives all three in one
|
||||
/// answer). Then the same as by the page: what the profile says, the first page saved, the gap below it filled by
|
||||
/// the next pages, when they are configured. The list of collections, when it has an operation of its own, comes
|
||||
/// last (a stop on it loses nothing already read; a refused permit leaves it for the next check), at most once every
|
||||
/// <see cref="RecipeOptions.HighlightsTrayInterval"/> and only for an account that wants its collections, always on a
|
||||
/// manual run. An answer of the posts or of the list that the readers do not know is an unrecognized format.
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> ProfileCheckByRequestsAsync(RecipeRun run)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
var profileOperation = Catalog.ForRole(RequestRole.Profile)!;
|
||||
var reply = await AskAsync(run, profileOperation, AccountValues(account), null, account.Id, RequestGap.None).ConfigureAwait(false);
|
||||
if (reply.NotFound)
|
||||
{
|
||||
await ProfileNotFoundAsync(run, account).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var reads = new List<CapturedRead>(reply.Reads);
|
||||
if (!run.Judge(reads, r => ProfileIn(r, account) is not null, profileOperation.PathShape))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
account = await ApplyProfileStateAsync(run, account, AccountProfile(reads, account)!).ConfigureAwait(false);
|
||||
var asked = new List<SiteOperation> { profileOperation };
|
||||
|
||||
var postsOperation = Catalog.ForRole(RequestRole.Posts)!;
|
||||
if (!asked.Contains(postsOperation))
|
||||
{
|
||||
reply = await AskAsync(run, postsOperation, AccountValues(account), null, account.Id, RequestGap.AfterAnswer).ConfigureAwait(false);
|
||||
var checkedAccount = account;
|
||||
JudgeUnknown(run, reply, r => IsWalkPage(r, checkedAccount, ProfileWalk.Posts));
|
||||
reads.AddRange(reply.Reads);
|
||||
asked.Add(postsOperation);
|
||||
}
|
||||
|
||||
var highlightsOperation = Catalog.ForRole(RequestRole.Highlights)!;
|
||||
var highlights = asked.Contains(highlightsOperation);
|
||||
if (highlights)
|
||||
{
|
||||
await HighlightsTrayReadAsync(run, account).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await RecordCheckedProfileAsync(run, account, AccountProfile(reads, account)!, reads, highlights).ConfigureAwait(false);
|
||||
var (items, tailIsNew, fillGap) = await SaveFirstGridPageAsync(run, account, reads).ConfigureAwait(false);
|
||||
if (fillGap)
|
||||
{
|
||||
await FillGapByRequestsAsync(run, account, reads, items, tailIsNew).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!highlights && await HighlightsTrayDueAsync(run, account).ConfigureAwait(false))
|
||||
{
|
||||
try
|
||||
{
|
||||
reply = await AskAsync(run, highlightsOperation, AccountValues(account), null, account.Id, RequestGap.AfterAnswer).ConfigureAwait(false);
|
||||
}
|
||||
catch (RecipeStopException stop) when (stop.Status == RecipeStatus.Denied)
|
||||
{
|
||||
// No permit, or the session is over: the check itself is done, the list waits for the next one.
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
if (!reply.NotFound)
|
||||
{
|
||||
JudgeUnknown(run, reply, r => r.Highlights.Count > 0);
|
||||
await UpsertListedHighlightsAsync(run, account, reply.Reads).ConfigureAwait(false);
|
||||
await HighlightsTrayReadAsync(run, account).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An answer whose content the recipe takes as it comes (none may be a fact of the profile): judged only when the
|
||||
/// readers did not recognize part of it, which stops the run as an unrecognized format.
|
||||
/// </summary>
|
||||
private static void JudgeUnknown(RecipeRun run, RequestReply reply, Func<ReadResult, bool> expected)
|
||||
{
|
||||
if (!reply.NotFound && reply.Reads.Any(r => r.Result.Shape == ReadShape.Unrecognized))
|
||||
{
|
||||
run.Judge(reply.Reads, expected, reply.Operation.PathShape);
|
||||
}
|
||||
}
|
||||
|
||||
private Task HighlightsTrayReadAsync(RecipeRun run, Account account) =>
|
||||
Env.Storage.Settings.SetAsync(HighlightsTrayKey(account.Id), Env.Clock.Now.ToString("O", CultureInfo.InvariantCulture), run.Ct);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the list of collections is to be asked this time: only for an account that wants its collections, then
|
||||
/// never asked, older than the interval, or a manual run.
|
||||
/// </summary>
|
||||
private async Task<bool> HighlightsTrayDueAsync(RecipeRun run, Account account)
|
||||
{
|
||||
if (!CollectionWriter.Wants(account, EntryKind.Highlight))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (run.Request.Manual)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var last = ParseTime(await Env.Storage.Settings.GetAsync(HighlightsTrayKey(account.Id), run.Ct).ConfigureAwait(false));
|
||||
return last is not { } at || Env.Clock.Now - at >= Env.Options.HighlightsTrayInterval;
|
||||
}
|
||||
|
||||
/// <summary>The site said the profile is not there (a 404 with JSON): the account is unreachable, as by the page.</summary>
|
||||
private async Task ProfileNotFoundAsync(RecipeRun run, Account account)
|
||||
{
|
||||
await MarkUnreachableAsync(run, account, UnreachableReason.NotFound).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"Il profilo {account.Username} non esiste o non è più disponibile.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The gap below the first page of a check, by requests (<see cref="FillGapAsync"/>): from the cursor of the first
|
||||
/// page when its last post was new, otherwise from the stored point; at most
|
||||
/// <see cref="RecipeOptions.GapPagesPerCheck"/> pages, until known posts. Without a request for the next pages the
|
||||
/// point is stored and the timeline says so. A refused permit, the end of the session or too many files waiting for
|
||||
/// download leave the gap for later.
|
||||
/// </summary>
|
||||
private async Task FillGapByRequestsAsync(RecipeRun run, Account account, IReadOnlyList<CapturedRead> reads, IReadOnlyList<ContentItem> firstPage, bool tailIsNew)
|
||||
{
|
||||
var walk = ProfileWalk.Gap;
|
||||
var settings = Env.Storage.Settings;
|
||||
var keys = new[] { walk.CursorKey(account.Id), walk.MarkKey(account.Id), walk.KnownBeforeKey(account.Id) };
|
||||
var storedCursor = await settings.GetAsync(keys[0], run.Ct).ConfigureAwait(false);
|
||||
var stored = storedCursor is null ? null : ResumePoint.Parse(storedCursor, await settings.GetAsync(keys[1], run.Ct).ConfigureAwait(false));
|
||||
var before = ParseTime(await settings.GetAsync(keys[2], run.Ct).ConfigureAwait(false));
|
||||
async Task ClearAsync() => await settings.SetManyAsync(keys.ToDictionary(k => k, _ => (string?)null), run.Ct).ConfigureAwait(false);
|
||||
|
||||
var first = WalkPage(reads, account, walk, ownAnswer: false);
|
||||
if (first?.HasMore == false)
|
||||
{
|
||||
if (stored is not null || before is not null)
|
||||
{
|
||||
await ClearAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var floor = Earliest(before, stored?.LastAt);
|
||||
Task StoreAsync(string cursor, ContentItem? last) => settings.SetManyAsync(
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
[keys[0]] = cursor,
|
||||
[keys[1]] = ResumePoint.MarkOf(last),
|
||||
[keys[2]] = floor?.ToString("O", CultureInfo.InvariantCulture),
|
||||
},
|
||||
run.Ct);
|
||||
|
||||
string? cursor;
|
||||
if (tailIsNew)
|
||||
{
|
||||
cursor = first?.Cursor;
|
||||
if (cursor is not null)
|
||||
{
|
||||
await StoreAsync(cursor, firstPage.LastOrDefault()).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
cursor = stored?.Cursor;
|
||||
}
|
||||
|
||||
if (cursor is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var next = Catalog.ForRole(RequestRole.PostsNext);
|
||||
if (next is null)
|
||||
{
|
||||
await NextPagesNotConfiguredAsync(run, account.Id).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var end = await WalkRequestPagesAsync(run, account, walk, next, cursor, new WalkRules
|
||||
{
|
||||
MaxPages = Math.Max(1, Env.Options.GapPagesPerCheck),
|
||||
Stop = floor is { } f ? new KnownStop(true, f) : KnownStop.Any,
|
||||
CheckDownloads = true,
|
||||
AnnounceSuspension = false,
|
||||
Processed = new HashSet<string>(firstPage.Select(i => i.Id), StringComparer.Ordinal),
|
||||
Store = StoreAsync,
|
||||
}).ConfigureAwait(false);
|
||||
if (end is WalkEnd.EndOfList or WalkEnd.Limit or WalkEnd.Known)
|
||||
{
|
||||
await ClearAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (RecipeStopException stop) when (stop.Status == RecipeStatus.Denied)
|
||||
{
|
||||
// No permit, the session is over, or too many files wait for download: the gap waits for the next check.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Storico, Taggati and Reel by requests (spec §6.3): the same stored point, rules and end as by the page
|
||||
/// (<see cref="WalkAsync"/>), but the point is never looked for by scrolling: the cursor is asked for directly. The
|
||||
/// first page of the grid comes with the profile (one ProfileOpen, not counted among the pages of the run, as by the
|
||||
/// page); the first page of a tab is counted. Without a request for the next pages the stored point stays.
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> WalkByRequestsAsync(RecipeRun run, ProfileWalk walk, RequestRole firstRole, RequestRole nextRole)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
if (await WalkStartAsync(run, account, walk).ConfigureAwait(false) is not { } start)
|
||||
{
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
var (cursor, checkOnly) = start;
|
||||
|
||||
if (!checkOnly)
|
||||
{
|
||||
await EnsureBackfillAllowedAsync(run, account).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var next = Catalog.ForRole(nextRole);
|
||||
var rules = new WalkRules
|
||||
{
|
||||
MaxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.PagesPerRun),
|
||||
Stop = checkOnly ? KnownStop.Any : KnownStop.Never,
|
||||
CheckDownloads = !checkOnly,
|
||||
Store = (point, last) => StoreWalkPointAsync(run, account, walk, point, last),
|
||||
};
|
||||
|
||||
WalkEnd end;
|
||||
if (cursor is not null && next is not null)
|
||||
{
|
||||
end = await WalkRequestPagesAsync(run, account, walk, next, cursor, rules).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (cursor is not null)
|
||||
{
|
||||
// A stored point and no request for the page after it (nor pages that could go on from it): the walk
|
||||
// waits there, and the first page is read for what is new on top. The point stays as it is.
|
||||
checkOnly = true;
|
||||
rules = rules with { MaxPages = 1, Stop = KnownStop.Any, Store = (_, _) => Task.CompletedTask };
|
||||
}
|
||||
|
||||
var firstOperation = Catalog.ForRole(firstRole)!;
|
||||
var reply = await AskAsync(run, firstOperation, AccountValues(account), null, account.Id, RequestGap.None).ConfigureAwait(false);
|
||||
if (reply.NotFound)
|
||||
{
|
||||
await ProfileNotFoundAsync(run, account).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (AccountProfile(reply.Reads, account) is { } profile)
|
||||
{
|
||||
account = await ApplyProfileStateAsync(run, account, profile).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!run.Judge(reply.Reads, r => IsWalkPage(r, account, walk), firstOperation.PathShape))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
end = await WalkRequestPagesAsync(run, account, walk, next, reply.Reads, rules with { PagesRead = walk.IsGrid ? 0 : 1 }).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (next is null && (end == WalkEnd.NoNext || (cursor is not null && end != WalkEnd.EndOfList)))
|
||||
{
|
||||
await NextPagesNotConfiguredAsync(run, account.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await FinishWalkAsync(run, account, walk, end, checkOnly, caughtUp: true, catchUpPages: 0).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>The pages of a walk by requests from a stored cursor: the first request is for the page after it.</summary>
|
||||
private Task<WalkEnd> WalkRequestPagesAsync(RecipeRun run, Account account, ProfileWalk walk, SiteOperation next, string cursor, WalkRules rules) =>
|
||||
WalkRequestPagesAsync(run, account, walk, next, null, rules, cursor);
|
||||
|
||||
/// <summary>
|
||||
/// The pages of a walk by requests, from a page in hand (<paramref name="reads"/>) or from <paramref name="cursor"/>:
|
||||
/// each page saved, then the end of the profile, a history limit, known content (when the rules say so), the pages
|
||||
/// of the run, or a page that cannot be asked (<see cref="WalkEnd.NoNext"/>); otherwise its point stored and the next
|
||||
/// page asked with its cursor, one permit each (<see cref="SiteOperation.CategoryFor"/>). A «not found» or an empty
|
||||
/// answer ends the walk as an empty page (<see cref="WalkEnd.NoData"/>).
|
||||
/// </summary>
|
||||
private async Task<WalkEnd> WalkRequestPagesAsync(RecipeRun run, Account account, ProfileWalk walk, SiteOperation? next, IReadOnlyList<CapturedRead>? reads, WalkRules rules, string? cursor = null)
|
||||
{
|
||||
var pages = rules.PagesRead;
|
||||
IReadOnlySet<string>? seen = null; // a first page in hand: only what its own answer brings
|
||||
while (true)
|
||||
{
|
||||
if (reads is null)
|
||||
{
|
||||
if (next is null || cursor is null)
|
||||
{
|
||||
return WalkEnd.NoNext;
|
||||
}
|
||||
|
||||
if (rules.CheckDownloads)
|
||||
{
|
||||
await EnsureBackfillAllowedAsync(run, account, rules.AnnounceSuspension).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var reply = await AskAsync(run, next, AccountValues(account), cursor, account.Id, RequestGap.BetweenPages).ConfigureAwait(false);
|
||||
pages++;
|
||||
if (reply.NotFound || !run.Judge(reply.Reads, r => IsWalkPage(r, account, walk), null))
|
||||
{
|
||||
return WalkEnd.NoData;
|
||||
}
|
||||
|
||||
reads = reply.Reads;
|
||||
seen = rules.Processed;
|
||||
}
|
||||
|
||||
var items = PageItems(reads, account, walk);
|
||||
var page = WalkPage(reads, account, walk, ownAnswer: true, seen);
|
||||
var (reachedKnown, reachedLimit) = await SaveWalkPageAsync(run, account, walk, items, rules.Processed, rules.Stop).ConfigureAwait(false);
|
||||
if (reachedLimit)
|
||||
{
|
||||
return WalkEnd.Limit;
|
||||
}
|
||||
|
||||
if (page?.HasMore == false)
|
||||
{
|
||||
return WalkEnd.EndOfList;
|
||||
}
|
||||
|
||||
if (reachedKnown)
|
||||
{
|
||||
return WalkEnd.Known;
|
||||
}
|
||||
|
||||
if (page?.Cursor is not { } following)
|
||||
{
|
||||
return WalkEnd.NoNext;
|
||||
}
|
||||
|
||||
await rules.Store(following, items.LastOrDefault()).ConfigureAwait(false);
|
||||
if (pages >= rules.MaxPages)
|
||||
{
|
||||
return WalkEnd.Pages;
|
||||
}
|
||||
|
||||
cursor = following;
|
||||
reads = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where a walk of Storico, Taggati or Reel starts, whatever turns its pages: the stored cursor and whether the walk
|
||||
/// only checks the first page (the tab was walked to the end). Null when there is nothing to do: the history of the
|
||||
/// grid is complete. Stops the run when the account does not want the content of the walk.
|
||||
/// </summary>
|
||||
private async Task<(string? Cursor, bool CheckOnly)?> WalkStartAsync(RecipeRun run, Account account, ProfileWalk walk)
|
||||
{
|
||||
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}.");
|
||||
}
|
||||
|
||||
if (walk.IsGrid)
|
||||
{
|
||||
if (account.BackfillCompletedAt is not null)
|
||||
{
|
||||
run.Finished = true;
|
||||
return null;
|
||||
}
|
||||
|
||||
return (account.BackfillCursor, false);
|
||||
}
|
||||
|
||||
var settings = Env.Storage.Settings;
|
||||
var checkOnly = await settings.GetAsync(walk.CompletedKey(account.Id), run.Ct).ConfigureAwait(false) is not null;
|
||||
var cursor = checkOnly ? null : await settings.GetAsync(walk.CursorKey(account.Id), run.Ct).ConfigureAwait(false);
|
||||
return (cursor, checkOnly);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Pacing;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
public sealed partial class RecipeRunner
|
||||
{
|
||||
/// <summary>
|
||||
/// Storie di un account by requests (spec §6.3): one request (one StoryView) gives the active stories of the
|
||||
/// account, all saved; no viewer, so no minimum of stories left in the budget. No story is a quiet day, not an
|
||||
/// empty page: only an answer the readers do not recognize is judged, and a recognized one counts as data. A «not
|
||||
/// found» is not a quiet day yet: the account may be gone, or private and no longer followed (rule 6), which the
|
||||
/// browser learns by opening the profile first. So the profile is asked (one ProfileOpen), as by the page, and says
|
||||
/// which; without a profile operation the «not found» counts as an empty page.
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> AccountStoriesByRequestsAsync(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}.");
|
||||
}
|
||||
|
||||
// No wait before the one request, not even after the stories of another account: the Governor keeps the
|
||||
// distance from the previous action (§6.3, §7.7).
|
||||
var operation = Catalog.ForRole(RequestRole.Stories)!;
|
||||
var profileOperation = Catalog.ForRole(RequestRole.Profile);
|
||||
var reply = await AskAsync(run, operation, AccountValues(account), null, account.Id, RequestGap.None, notFoundIsEmpty: profileOperation is null).ConfigureAwait(false);
|
||||
if (reply.NotFound)
|
||||
{
|
||||
if (profileOperation is not null)
|
||||
{
|
||||
await StoriesNotFoundAsync(run, account, profileOperation).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
bool IsStory(ContentItem c) => IsOwnedBy(c, account) && c.ExpiresAt is not null && c.HighlightId is null;
|
||||
if (reply.Reads.Any(r => r.Result.Shape == ReadShape.Unrecognized))
|
||||
{
|
||||
run.Judge(reply.Reads, r => r.Contents.Any(IsStory), null);
|
||||
}
|
||||
else if (reply.Reads.Any(r => r.Result.Shape == ReadShape.Recognized))
|
||||
{
|
||||
run.SawData();
|
||||
}
|
||||
|
||||
foreach (var story in Contents(reply.Reads, IsStory))
|
||||
{
|
||||
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.Ct).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The stories of an account were «not found»: the profile says why. Gone: unreachable (a «not found» of the
|
||||
/// profile, counted as an empty page). Private and not followed: unreachable, never touched again (rule 6). Otherwise
|
||||
/// a day without stories. Each case as by the page (<see cref="ApplyProfileStateAsync"/>).
|
||||
/// </summary>
|
||||
private async Task StoriesNotFoundAsync(RecipeRun run, Account account, SiteOperation profileOperation)
|
||||
{
|
||||
var reply = await AskAsync(run, profileOperation, AccountValues(account), null, account.Id, RequestGap.AfterAnswer).ConfigureAwait(false);
|
||||
if (reply.NotFound)
|
||||
{
|
||||
await ProfileNotFoundAsync(run, account).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!run.Judge(reply.Reads, r => ProfileIn(r, account) is not null, profileOperation.PathShape))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
await ApplyProfileStateAsync(run, account, AccountProfile(reply.Reads, account)!).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raccolta in evidenza by requests (spec §6.3): the collection must be known already (the profile check lists the
|
||||
/// collections); one request (one StoryView) per page of its contents, each content linked to its entry (a story
|
||||
/// already saved is referenced, not downloaded again, H9). The order of the collection is stored only when all its
|
||||
/// pages were read.
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> HighlightByRequestsAsync(RecipeRun run)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
if (run.Request.HighlightId is not { Length: > 0 } requested)
|
||||
{
|
||||
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}.");
|
||||
}
|
||||
|
||||
var highlightId = ShapeReader.HighlightId(requested);
|
||||
var highlight = await Env.Storage.Highlights.FindAsync(account.Id, highlightId, run.Ct).ConfigureAwait(false)
|
||||
?? (requested == highlightId ? null : await Env.Storage.Highlights.FindAsync(account.Id, requested, run.Ct).ConfigureAwait(false))
|
||||
?? throw RecipeRun.Stop(RecipeStatus.Completed, "La raccolta non è ancora nota: la legge il prossimo controllo del profilo.");
|
||||
|
||||
var values = AccountValues(account);
|
||||
Put(values, CaseValues.HighlightId, highlight.InstagramId);
|
||||
var operation = Catalog.ForRole(RequestRole.Highlight)!;
|
||||
if (operation.RequiredValues.Contains(CaseValues.HighlightId) && !values.ContainsKey(CaseValues.HighlightId))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, $"Per la raccolta «{highlight.Title}» di {account.Username} manca {ValueName(CaseValues.HighlightId)}; si riprova al prossimo giro.");
|
||||
}
|
||||
|
||||
bool Inside(ContentItem c) => InCollection(c, highlightId);
|
||||
bool Expected(ReadResult r) => r.Contents.Any(Inside) || r.Highlights.Any(h => h.Id == highlightId);
|
||||
var reply = await AskAsync(run, operation, values, null, account.Id, RequestGap.None).ConfigureAwait(false);
|
||||
if (reply.NotFound)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, $"La raccolta «{highlight.Title}» non è più nel profilo: i suoi file restano.");
|
||||
}
|
||||
|
||||
if (!run.Judge(reply.Reads, Expected, operation.PathShape))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
// Each page is linked as soon as it is read: a stop on a later page (a refused permit, a signal, an error) keeps
|
||||
// what was already read and paid for, as the viewer keeps what it showed.
|
||||
var items = Contents(reply.Reads, Inside);
|
||||
var seen = new HashSet<string>(items.Select(i => i.Id), StringComparer.Ordinal);
|
||||
var ordered = new List<long>();
|
||||
var linkedAll = await LinkHighlightPageAsync(run, account, highlight, items, ordered).ConfigureAwait(false);
|
||||
var page = PageOf(reply.Reads, r => r.Contents.Where(Inside).Select(c => c.Id), r => r.Shape == ReadShape.Empty);
|
||||
var next = Catalog.ForRole(RequestRole.HighlightNext);
|
||||
var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.PagesPerRun);
|
||||
var pages = 1;
|
||||
while (page is { HasMore: true, Cursor: { } cursor } && next is not null && pages < maxPages)
|
||||
{
|
||||
reply = await AskAsync(run, next, values, cursor, account.Id, RequestGap.BetweenPages).ConfigureAwait(false);
|
||||
pages++;
|
||||
if (reply.NotFound || !run.Judge(reply.Reads, Expected, null))
|
||||
{
|
||||
break; // an empty page: the order of the collection is not stored this time
|
||||
}
|
||||
|
||||
var more = Contents(reply.Reads, c => Inside(c) && !seen.Contains(c.Id));
|
||||
page = PageOf(reply.Reads, r => r.Contents.Where(Inside).Select(c => c.Id), r => r.Shape == ReadShape.Empty, seen);
|
||||
items.AddRange(more);
|
||||
seen.UnionWith(more.Select(i => i.Id));
|
||||
linkedAll &= await LinkHighlightPageAsync(run, account, highlight, more, ordered).ConfigureAwait(false);
|
||||
if (more.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Read to the end only when the last page says so: a cap of the run, an empty page or a page with nothing new
|
||||
// leave the order of the collection as it was (rule 11), only links added.
|
||||
var complete = page?.HasMore != true;
|
||||
if (!complete && next is null)
|
||||
{
|
||||
await NextPagesNotConfiguredAsync(run, account.Id, pointKept: false).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (complete && items.Count > 0 && linkedAll)
|
||||
{
|
||||
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);
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>Links the contents of one page of a collection to their entries; true when every one has its entry.</summary>
|
||||
private async Task<bool> LinkHighlightPageAsync(RecipeRun run, Account account, Highlight highlight, IReadOnlyList<ContentItem> items, List<long> ordered)
|
||||
{
|
||||
var all = true;
|
||||
foreach (var item in items)
|
||||
{
|
||||
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);
|
||||
}
|
||||
else
|
||||
{
|
||||
all = false;
|
||||
}
|
||||
}
|
||||
|
||||
return all;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
public sealed partial class RecipeRunner
|
||||
{
|
||||
/// <summary>
|
||||
/// The roles a recipe needs to go by requests (issue #36, S3), and the role that goes on to the next page when there
|
||||
/// is one. The Giro dei seguiti never goes by requests in S3: its operations have no samples.
|
||||
/// </summary>
|
||||
public static (IReadOnlyList<RequestRole> Required, RequestRole? Next) RequestNeeds(RecipeKind kind) => kind switch
|
||||
{
|
||||
RecipeKind.ProfileCheck => ([RequestRole.Profile, RequestRole.Posts, RequestRole.Highlights], RequestRole.PostsNext),
|
||||
RecipeKind.Backfill => ([RequestRole.Posts, RequestRole.PostsNext], null),
|
||||
RecipeKind.Tagged => ([RequestRole.Tagged], RequestRole.TaggedNext),
|
||||
RecipeKind.Reels => ([RequestRole.Reels], RequestRole.ReelsNext),
|
||||
RecipeKind.AccountStories => ([RequestRole.Stories], null),
|
||||
RecipeKind.Highlight => ([RequestRole.Highlight], RequestRole.HighlightNext),
|
||||
RecipeKind.SinglePost => ([RequestRole.Post], null),
|
||||
RecipeKind.FollowingList => ([RequestRole.Following], RequestRole.FollowingNext),
|
||||
_ => ([], null),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The operations of <paramref name="catalog"/> that let <paramref name="kind"/> go by requests, in the order of its
|
||||
/// roles and without repetitions; null when a role it needs is missing or not configured.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<SiteOperation>? RequestOperations(RequestCatalog catalog, RecipeKind kind)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(catalog);
|
||||
var (required, next) = RequestNeeds(kind);
|
||||
if (required.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var operations = new List<SiteOperation>();
|
||||
foreach (var role in required)
|
||||
{
|
||||
if (catalog.ForRole(role) is not { } operation)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!operations.Contains(operation))
|
||||
{
|
||||
operations.Add(operation);
|
||||
}
|
||||
}
|
||||
|
||||
if (next is { } more && catalog.ForRole(more) is { } continuation && !operations.Contains(continuation))
|
||||
{
|
||||
operations.Add(continuation);
|
||||
}
|
||||
|
||||
return operations;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="kind"/> goes by requests: the site client is there and every role the recipe needs is
|
||||
/// a configured operation of its catalog. On Instagram nothing is configured yet: always false.
|
||||
/// </summary>
|
||||
public bool HasRequestRoute(RecipeKind kind) =>
|
||||
Env.Requests is { } requests && kind != RecipeKind.FollowingSweep && RequestOperations(requests.Catalog, kind) is not null;
|
||||
|
||||
/// <summary>
|
||||
/// The budget category of the first action of <paramref name="kind"/> on its route: by requests, the category of
|
||||
/// the operation of its first role (Taggati and Reel start with a page of the tab, BackfillPage, not with the
|
||||
/// profile); by the pages, and for the Storico (whose first page counts as the profile without a stored point and
|
||||
/// as a page with one, the same on both routes), <see cref="CheckPolicy.CategoryOf"/>.
|
||||
/// </summary>
|
||||
public ActionKind FirstCategory(RecipeKind kind) =>
|
||||
kind != RecipeKind.Backfill && HasRequestRoute(kind) && Catalog.ForRole(RequestNeeds(kind).Required[0]) is { } first
|
||||
? first.Category
|
||||
: CheckPolicy.CategoryOf(kind);
|
||||
|
||||
private RequestCatalog Catalog => Env.Requests!.Catalog;
|
||||
|
||||
/// <summary>
|
||||
/// Whether this run can go by requests: every value its first requests need is known (the identifier of the
|
||||
/// account, the code of the post…). When one is missing the run goes by the pages, if they can run, with an Info
|
||||
/// line; otherwise it ends <see cref="RecipeStatus.Completed"/> with an Info line and is tried again at the next round
|
||||
/// (never <see cref="RecipeStatus.NotConfigured"/>: the engine would not plan it again in this process). A missing
|
||||
/// saved session is not a missing value: it is a disconnection (rule 7), never a way back to the pages.
|
||||
/// </summary>
|
||||
private async Task<bool> ChooseRequestRouteAsync(RecipeRun run)
|
||||
{
|
||||
var (missing, who) = await MissingRequestValueAsync(run).ConfigureAwait(false);
|
||||
if (missing is null)
|
||||
{
|
||||
if (Refusal(run.Request.Kind) is null && await NextPagesNeededAsync(run).ConfigureAwait(false))
|
||||
{
|
||||
// A stored point whose next page has no request: the pages can go on from it, the requests cannot.
|
||||
await Writer.EventAsync("richieste-pagine-successive", $"Le pagine successive di «{Name(run.Request.Kind)}» non sono ancora configurate per le richieste: questa volta si passa dalle pagine.", EventSeverity.Info, run.Request.AccountId, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Refusal(run.Request.Kind) is null)
|
||||
{
|
||||
await Writer.EventAsync("richieste-valore-mancante", $"«{Name(run.Request.Kind)}»{(who is null ? string.Empty : $" di {who}")}: manca {missing}, questa volta si passa dalle pagine.", EventSeverity.Info, run.Request.AccountId, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
var message = $"Per {who ?? $"«{Name(run.Request.Kind)}»"} manca {missing}; si riprova al prossimo giro.";
|
||||
await Writer.EventAsync("richieste-valore-mancante", message, EventSeverity.Info, run.Request.AccountId, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the run would start from a stored point (Taggati, Reel, Elenco dei seguiti) whose next page has no
|
||||
/// configured request: by requests it could not go on.
|
||||
/// </summary>
|
||||
private async Task<bool> NextPagesNeededAsync(RecipeRun run)
|
||||
{
|
||||
var kind = run.Request.Kind;
|
||||
if (RequestNeeds(kind).Next is not { } nextRole || Catalog.ForRole(nextRole) is not null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var settings = Env.Storage.Settings;
|
||||
switch (kind)
|
||||
{
|
||||
case RecipeKind.Tagged or RecipeKind.Reels when run.Request.AccountId is { } id:
|
||||
var walk = kind == RecipeKind.Tagged ? ProfileWalk.Tagged : ProfileWalk.Reels;
|
||||
return await settings.GetAsync(walk.CompletedKey(id), run.Ct).ConfigureAwait(false) is null
|
||||
&& await settings.GetAsync(walk.CursorKey(id), run.Ct).ConfigureAwait(false) is not null;
|
||||
case RecipeKind.FollowingList:
|
||||
return await settings.GetAsync(FollowingKeys.Cursor, run.Ct).ConfigureAwait(false) is not null
|
||||
&& await settings.GetAsync(FollowingKeys.StartedAt, run.Ct).ConfigureAwait(false) is not null;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first value of the case the first requests of the run need and do not have, in Italian, with the user name
|
||||
/// it is missing for; (null, null) when nothing is missing, or when what is missing is the run's own data (no account,
|
||||
/// no entry), which the recipe reports itself.
|
||||
/// </summary>
|
||||
private async Task<(string? Missing, string? Who)> MissingRequestValueAsync(RecipeRun run)
|
||||
{
|
||||
Dictionary<string, string> available;
|
||||
string? who;
|
||||
var request = run.Request;
|
||||
switch (request.Kind)
|
||||
{
|
||||
case RecipeKind.SinglePost:
|
||||
{
|
||||
var entry = request.EntryId is { } entryId ? await Env.Storage.Entries.GetAsync(entryId, run.Ct).ConfigureAwait(false) : null;
|
||||
var account = entry is null ? null : await Env.Storage.Accounts.GetAsync(entry.AccountId, run.Ct).ConfigureAwait(false);
|
||||
if (entry is null || account is null)
|
||||
{
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
available = AccountValues(account);
|
||||
Put(available, CaseValues.Code, entry.Code);
|
||||
Put(available, CaseValues.MediaId, entry.InstagramId);
|
||||
who = account.Username;
|
||||
break;
|
||||
}
|
||||
|
||||
case RecipeKind.FollowingList:
|
||||
{
|
||||
var mine = await Env.Storage.Accounts.GetMineAsync(run.Ct).ConfigureAwait(false);
|
||||
available = mine is null ? new Dictionary<string, string>(StringComparer.Ordinal) : AccountValues(mine);
|
||||
who = null;
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
var account = request.AccountId is { } id ? await Env.Storage.Accounts.GetAsync(id, run.Ct).ConfigureAwait(false) : null;
|
||||
if (account is null)
|
||||
{
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
available = AccountValues(account);
|
||||
who = account.Username;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var role in RequestNeeds(request.Kind).Required)
|
||||
{
|
||||
var operation = Catalog.ForRole(role)!;
|
||||
|
||||
// The collection of a Raccolta in evidenza is looked up by the recipe: unknown, it ends without a request.
|
||||
foreach (var name in operation.RequiredValues.Where(v => v is not (CaseValues.Cursor or CaseValues.HighlightId)))
|
||||
{
|
||||
if (!available.ContainsKey(name))
|
||||
{
|
||||
return (ValueName(name), who);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
/// <summary>The values of the case an account gives: its user name and, once known, its identifier.</summary>
|
||||
private static Dictionary<string, string> AccountValues(Account account)
|
||||
{
|
||||
var values = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
Put(values, CaseValues.Username, account.Username);
|
||||
Put(values, CaseValues.AccountId, account.InstagramId);
|
||||
return values;
|
||||
}
|
||||
|
||||
/// <summary>Adds a value only when it has the form of its name (<see cref="CaseValues.HasForm"/>): one without is missing.</summary>
|
||||
private static void Put(Dictionary<string, string> values, string name, string? value)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(value) && CaseValues.HasForm(name, value))
|
||||
{
|
||||
values[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
private static string ValueName(string name) => name switch
|
||||
{
|
||||
CaseValues.AccountId => "l'identificativo dell'account",
|
||||
CaseValues.Username => "il nome utente",
|
||||
CaseValues.Code => "il codice del post",
|
||||
CaseValues.MediaId => "l'identificativo del post",
|
||||
CaseValues.HighlightId => "l'identificativo della raccolta",
|
||||
_ => $"il valore «{name}»",
|
||||
};
|
||||
|
||||
/// <summary>The recipe by requests (spec §6.3, column «Per richieste»): the page is never touched.</summary>
|
||||
private Task<RecipeStatus> RunByRequestsAsync(RecipeRun run) => run.Request.Kind switch
|
||||
{
|
||||
RecipeKind.ProfileCheck => ProfileCheckByRequestsAsync(run),
|
||||
RecipeKind.Backfill => WalkByRequestsAsync(run, ProfileWalk.Posts, RequestRole.Posts, RequestRole.PostsNext),
|
||||
RecipeKind.Tagged => WalkByRequestsAsync(run, ProfileWalk.Tagged, RequestRole.Tagged, RequestRole.TaggedNext),
|
||||
RecipeKind.Reels => WalkByRequestsAsync(run, ProfileWalk.Reels, RequestRole.Reels, RequestRole.ReelsNext),
|
||||
RecipeKind.AccountStories => AccountStoriesByRequestsAsync(run),
|
||||
RecipeKind.Highlight => HighlightByRequestsAsync(run),
|
||||
RecipeKind.SinglePost => SinglePostByRequestsAsync(run),
|
||||
RecipeKind.FollowingList => FollowingListByRequestsAsync(run),
|
||||
_ => throw RecipeRun.Stop(RecipeStatus.Failed, $"«{Name(run.Request.Kind)}» non va per richieste."),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// One request of <paramref name="operation"/> with the values it takes from <paramref name="available"/>, and
|
||||
/// <paramref name="cursor"/> when it takes one (<see cref="RecipeRun.AskAsync"/>).
|
||||
/// </summary>
|
||||
private static Task<RequestReply> AskAsync(RecipeRun run, SiteOperation operation, IReadOnlyDictionary<string, string> available, string? cursor, long? accountId, RequestGap gap, bool notFoundIsEmpty = true)
|
||||
{
|
||||
var values = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var name in operation.RequiredValues.Concat(operation.OptionalValues))
|
||||
{
|
||||
if (name == CaseValues.Cursor)
|
||||
{
|
||||
if (cursor is not null)
|
||||
{
|
||||
values[name] = cursor;
|
||||
}
|
||||
}
|
||||
else if (available.TryGetValue(name, out var value))
|
||||
{
|
||||
values[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return run.AskAsync(operation, new SiteRequest(operation.Name, values), accountId, gap, notFoundIsEmpty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The pages after the one in hand cannot be asked: the role that goes on is not configured. Said once per run; the
|
||||
/// stored point stays (S4: configure the next pages before switching a recipe to requests). A Raccolta in evidenza
|
||||
/// keeps no point (<paramref name="pointKept"/> false): it starts again from its first page next time.
|
||||
/// </summary>
|
||||
private Task NextPagesNotConfiguredAsync(RecipeRun run, long? accountId, bool pointKept = true) =>
|
||||
Writer.EventAsync(
|
||||
"richieste-pagine-successive",
|
||||
$"Le pagine successive di «{Name(run.Request.Kind)}» non sono ancora configurate per le richieste: {(pointKept ? "il punto resta salvato." : "la prossima volta si ricomincia dalla prima pagina.")}",
|
||||
EventSeverity.Info,
|
||||
accountId,
|
||||
run.Session.SessionId,
|
||||
run.Ct);
|
||||
}
|
||||
@@ -50,6 +50,12 @@ public sealed record RecipeEnvironment
|
||||
/// action that opens a page, when the search waits. Null: no search, no turn points.
|
||||
/// </summary>
|
||||
public PageTurns? PageTurns { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The site client and its catalog (issue #36, S3): a recipe whose roles are all configured reads the site by
|
||||
/// requests, never touching the page. Null: every recipe goes by the browser (production until S4).
|
||||
/// </summary>
|
||||
public SiteRequestEnvironment? Requests { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -68,14 +74,23 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
private readonly Lock _refusalsGate = new();
|
||||
private readonly HashSet<RecipeKind> _refusalsReported = [];
|
||||
private long? _sessionId;
|
||||
private long? _kindSessionId;
|
||||
private RecipeKind? _lastKind;
|
||||
private long _requests;
|
||||
|
||||
public RecipeRunner(RecipeEnvironment environment)
|
||||
{
|
||||
Env = environment ?? throw new ArgumentNullException(nameof(environment));
|
||||
Writer = new CollectionWriter(environment.Storage, environment.Clock) { Diagnostics = environment.Diagnostics };
|
||||
Delivery = new ResponseDelivery("Client del sito", environment.Requests?.Warn is { } warn ? (message, _) => warn(message) : null);
|
||||
}
|
||||
|
||||
/// <summary>Hands the answers of the site client to the readers, as the response tap does for the page.</summary>
|
||||
internal ResponseDelivery Delivery { get; }
|
||||
|
||||
/// <summary>The number of the next request of the site client (its identifier for the readers and the diagnostics).</summary>
|
||||
internal long NextRequestNumber() => Interlocked.Increment(ref _requests);
|
||||
|
||||
public RecipeEnvironment Env { get; }
|
||||
|
||||
public CollectionWriter Writer { get; }
|
||||
@@ -130,8 +145,8 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
|
||||
// A map or a vocabulary that lacks what the recipe needs is a state of the configuration, not a failure of the
|
||||
// recipe: nothing is done, nothing counts towards suspension, and it is said once per recipe and process (the
|
||||
// engine stops planning it, NotConfiguredReason).
|
||||
if (Refusal(request.Kind) is { } refusal)
|
||||
// engine stops planning it, NotConfiguredReason). A recipe that can go by requests needs only the vocabulary.
|
||||
if (BlockingRefusal(request.Kind) is { } refusal)
|
||||
{
|
||||
bool first;
|
||||
lock (_refusalsGate)
|
||||
@@ -154,33 +169,32 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
return new RecipeOutcome(RecipeStatus.Denied, 0, 0, "L'interruttore è aperto: nessuna azione verso il sito.");
|
||||
}
|
||||
|
||||
if (_sessionId != session.SessionId)
|
||||
if (_kindSessionId != session.SessionId)
|
||||
{
|
||||
Env.Driver.BeginSession(session.Mood);
|
||||
_sessionId = session.SessionId;
|
||||
_kindSessionId = session.SessionId;
|
||||
_lastKind = null;
|
||||
}
|
||||
|
||||
// By requests the page is never touched: no gesture session, no cookie check of the browser (rule 7).
|
||||
var byRequests = HasRequestRoute(request.Kind);
|
||||
if (!byRequests)
|
||||
{
|
||||
BeginPageSession(session);
|
||||
}
|
||||
|
||||
using var run = new RecipeRun(this, request, session, ct);
|
||||
RecipeStatus status;
|
||||
string? text = null;
|
||||
string? errorType = null;
|
||||
try
|
||||
{
|
||||
await CheckSessionCookieAsync(run).ConfigureAwait(false);
|
||||
status = request.Kind switch
|
||||
if (byRequests && !await ChooseRequestRouteAsync(run).ConfigureAwait(false))
|
||||
{
|
||||
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}."),
|
||||
};
|
||||
byRequests = false;
|
||||
BeginPageSession(session);
|
||||
}
|
||||
|
||||
status = byRequests ? await RunByRequestsAsync(run).ConfigureAwait(false) : await RunByPagesAsync(run).ConfigureAwait(false);
|
||||
}
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
@@ -206,6 +220,44 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
errorType = ex.GetType().Name;
|
||||
}
|
||||
|
||||
return await EndAsync(run, status, text, errorType).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A new engine session for the page: the driver draws its mood once per session.</summary>
|
||||
private void BeginPageSession(ISessionContext session)
|
||||
{
|
||||
if (_sessionId != session.SessionId)
|
||||
{
|
||||
Env.Driver.BeginSession(session.Mood);
|
||||
_sessionId = session.SessionId;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The recipe by the browser: the session cookie of the page first, then the gestures (spec §6.3).</summary>
|
||||
private async Task<RecipeStatus> RunByPagesAsync(RecipeRun run)
|
||||
{
|
||||
var request = run.Request;
|
||||
await CheckSessionCookieAsync(run).ConfigureAwait(false);
|
||||
return 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}."),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>How a run ended, whatever route it took: the signal, the timeline, the diagnostics, the outcome.</summary>
|
||||
private async Task<RecipeOutcome> EndAsync(RecipeRun run, RecipeStatus status, string? text, string? errorType)
|
||||
{
|
||||
var request = run.Request;
|
||||
var session = run.Session;
|
||||
if (run.Signal is { } signal && status is not (RecipeStatus.StoppedBySignal or RecipeStatus.Cancelled))
|
||||
{
|
||||
status = RecipeStatus.StoppedBySignal;
|
||||
@@ -242,11 +294,19 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public string? NotConfiguredReason(RecipeKind kind) => Refusal(kind)?.Message;
|
||||
public string? NotConfiguredReason(RecipeKind kind) => BlockingRefusal(kind)?.Message;
|
||||
|
||||
/// <summary>
|
||||
/// Why the site's configuration does not let <paramref name="kind"/> run, with the code of its timeline line: pages
|
||||
/// or targets missing from the map, or a reader vocabulary that cannot be relied on. Null when it can run.
|
||||
/// What keeps <paramref name="kind"/> from running at all: with a request route (<see cref="HasRequestRoute"/>) only
|
||||
/// a reader vocabulary that cannot be relied on, otherwise everything <see cref="Refusal"/> says.
|
||||
/// </summary>
|
||||
private (string Code, string Message)? BlockingRefusal(RecipeKind kind) =>
|
||||
HasRequestRoute(kind) ? VocabularyRefusal(kind) : Refusal(kind);
|
||||
|
||||
/// <summary>
|
||||
/// Why the site's configuration does not let <paramref name="kind"/> run by the browser, with the code of its
|
||||
/// timeline line: pages or targets missing from the map, or a reader vocabulary that cannot be relied on. Null when
|
||||
/// it can run.
|
||||
/// </summary>
|
||||
private (string Code, string Message)? Refusal(RecipeKind kind)
|
||||
{
|
||||
@@ -258,11 +318,15 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
return ("mappa-incompleta", $"«{name}» non può girare su {Env.SiteMap.Site}: la mappa dei bersagli non è ancora compilata (mancano {string.Join(", ", missing)}).");
|
||||
}
|
||||
|
||||
return Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable
|
||||
? ("lettori-incompleti", $"«{name}» non può girare: {unusable}")
|
||||
: null;
|
||||
return VocabularyRefusal(kind);
|
||||
}
|
||||
|
||||
/// <summary>A reader vocabulary that cannot be relied on: no route can read the site with it.</summary>
|
||||
private (string Code, string Message)? VocabularyRefusal(RecipeKind kind) =>
|
||||
Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable
|
||||
? ("lettori-incompleti", $"«{Name(kind)}» non può girare: {unusable}")
|
||||
: null;
|
||||
|
||||
/// <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.
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
/// <summary>
|
||||
/// What the recipes need to read the site by requests instead of pages (issue #36, S3): the site client, the catalog
|
||||
/// with the roles of its operations, the reading of the stop signals in its answers, and the pace of the waits. Set in
|
||||
/// <see cref="RecipeEnvironment.Requests"/> only where a request route is wanted: until S4 only the tests set it, and in
|
||||
/// production every recipe goes by the browser.
|
||||
/// </summary>
|
||||
/// <param name="Requester">The site client (HTTP, or the test double): one request at a time, each with its permit.</param>
|
||||
/// <param name="Catalog">The operations of <c>richieste.<sito>.json</c> and their roles.</param>
|
||||
/// <param name="AnswerSignals">The stop signals of §7.6 read from the answers.</param>
|
||||
/// <param name="Pace">The «Ritmo dei gesti»: multiplies the waits between requests like the waits of the gestures.</param>
|
||||
/// <param name="Warn">Receives Italian warnings (names and shapes only, never values); null discards them.</param>
|
||||
public sealed record SiteRequestEnvironment(
|
||||
ISiteRequester Requester,
|
||||
RequestCatalog Catalog,
|
||||
SiteAnswerSignals AnswerSignals,
|
||||
GesturePace Pace = GesturePace.Natural,
|
||||
Action<string>? Warn = null);
|
||||
@@ -111,9 +111,11 @@ public static class SiteRequestGuard
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: intestazioni o campi senza una fonte stabilita.");
|
||||
}
|
||||
|
||||
if (permit.Kind != operation.Category)
|
||||
// The first page of a «storico» operation with «firstPageCategory» counts as the profile open (S3).
|
||||
var category = operation.CategoryFor(request);
|
||||
if (permit.Kind != category)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: il permesso è per {permit.Kind}, l'operazione conta come {operation.Category}.");
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: il permesso è per {permit.Kind}, la richiesta conta come {category}.");
|
||||
}
|
||||
|
||||
if (operation.CheckValues(request) is { } problem)
|
||||
|
||||
@@ -69,6 +69,90 @@ public sealed record ValueSource(ValueSourceKind Kind, string? Argument)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The part an operation plays in the recipes (issue #36, S3): the recipes ask for a role, never for an operation by
|
||||
/// name, because each site names its operations its own way. Written in <c>richieste.<sito>.json</c> as
|
||||
/// <c>"roles": [ ... ]</c> with the spellings of <see cref="RequestRoles"/>. A role belongs to one operation at most; a
|
||||
/// role on an operation that is not configured is not available (<see cref="RequestCatalog.ForRole"/>).
|
||||
/// </summary>
|
||||
public enum RequestRole
|
||||
{
|
||||
/// <summary>The profile of an account (<c>profile</c>).</summary>
|
||||
Profile,
|
||||
|
||||
/// <summary>The first page of the posts of a profile (<c>posts</c>).</summary>
|
||||
Posts,
|
||||
|
||||
/// <summary>A later page of the posts, from a cursor (<c>posts-next</c>).</summary>
|
||||
PostsNext,
|
||||
|
||||
/// <summary>The tray of the highlight collections of a profile (<c>highlights</c>).</summary>
|
||||
Highlights,
|
||||
|
||||
/// <summary>The first page of the posts an account is tagged in (<c>tagged</c>).</summary>
|
||||
Tagged,
|
||||
|
||||
/// <summary>A later page of the tagged posts (<c>tagged-next</c>).</summary>
|
||||
TaggedNext,
|
||||
|
||||
/// <summary>The first page of the reels of a profile (<c>reels</c>).</summary>
|
||||
Reels,
|
||||
|
||||
/// <summary>A later page of the reels (<c>reels-next</c>).</summary>
|
||||
ReelsNext,
|
||||
|
||||
/// <summary>The active stories of an account (<c>stories</c>).</summary>
|
||||
Stories,
|
||||
|
||||
/// <summary>The items of one highlight collection (<c>highlight</c>).</summary>
|
||||
Highlight,
|
||||
|
||||
/// <summary>A later page of the items of a collection (<c>highlight-next</c>).</summary>
|
||||
HighlightNext,
|
||||
|
||||
/// <summary>A single post (<c>post</c>).</summary>
|
||||
Post,
|
||||
|
||||
/// <summary>The first page of the list of profiles Alberto follows (<c>following</c>).</summary>
|
||||
Following,
|
||||
|
||||
/// <summary>A later page of that list (<c>following-next</c>).</summary>
|
||||
FollowingNext,
|
||||
}
|
||||
|
||||
/// <summary>The spellings of <see cref="RequestRole"/> in the catalog file.</summary>
|
||||
public static class RequestRoles
|
||||
{
|
||||
private static readonly FrozenDictionary<string, RequestRole> ByName = new Dictionary<string, RequestRole>(StringComparer.Ordinal)
|
||||
{
|
||||
["profile"] = RequestRole.Profile,
|
||||
["posts"] = RequestRole.Posts,
|
||||
["posts-next"] = RequestRole.PostsNext,
|
||||
["highlights"] = RequestRole.Highlights,
|
||||
["tagged"] = RequestRole.Tagged,
|
||||
["tagged-next"] = RequestRole.TaggedNext,
|
||||
["reels"] = RequestRole.Reels,
|
||||
["reels-next"] = RequestRole.ReelsNext,
|
||||
["stories"] = RequestRole.Stories,
|
||||
["highlight"] = RequestRole.Highlight,
|
||||
["highlight-next"] = RequestRole.HighlightNext,
|
||||
["post"] = RequestRole.Post,
|
||||
["following"] = RequestRole.Following,
|
||||
["following-next"] = RequestRole.FollowingNext,
|
||||
}.ToFrozenDictionary(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The role written as <paramref name="name"/>, or null for an unknown spelling.</summary>
|
||||
public static RequestRole? Parse(string? name) =>
|
||||
name is not null && ByName.TryGetValue(name.Trim(), out var role) ? role : null;
|
||||
|
||||
/// <summary>The spelling of <paramref name="role"/> in the file.</summary>
|
||||
public static string Name(RequestRole role) => ByName.First(p => p.Value == role).Key;
|
||||
|
||||
/// <summary>A role that goes on from a cursor of the previous answer (<c>-next</c>).</summary>
|
||||
public static bool IsNext(RequestRole role) =>
|
||||
role is RequestRole.PostsNext or RequestRole.TaggedNext or RequestRole.ReelsNext or RequestRole.HighlightNext or RequestRole.FollowingNext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One operation of <c>richieste.<sito>.json</c>: what the site client may ask (issue #36, spec §6.0). Written from
|
||||
/// the real request shapes of <c>febe-sonda richieste</c> (§14.5) and documented by a cleaned sample of its answer
|
||||
@@ -95,9 +179,13 @@ public sealed partial class SiteOperation
|
||||
IReadOnlySet<string> optional,
|
||||
IReadOnlyList<string> parameterOrder,
|
||||
IReadOnlyList<string> headerOrder,
|
||||
IReadOnlyList<string> bodyOrder)
|
||||
IReadOnlyList<string> bodyOrder,
|
||||
IReadOnlySet<RequestRole> roles,
|
||||
ActionKind? firstPageCategory)
|
||||
{
|
||||
Name = name;
|
||||
Roles = roles;
|
||||
FirstPageCategory = firstPageCategory;
|
||||
Kind = kind;
|
||||
Method = method;
|
||||
Path = path;
|
||||
@@ -148,6 +236,32 @@ public sealed partial class SiteOperation
|
||||
/// </summary>
|
||||
public ActionKind Category { get; }
|
||||
|
||||
/// <summary>The parts the operation plays in the recipes (<c>"roles"</c>, S3); empty when it plays none.</summary>
|
||||
public IReadOnlySet<RequestRole> Roles { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The category of the first page, asked without a cursor (<c>"firstPageCategory"</c>, only on a «storico»
|
||||
/// operation): <see cref="ActionKind.ProfileOpen"/>, because in the browser the first page of the grid came with the
|
||||
/// profile. Null: every request counts in <see cref="Category"/>.
|
||||
/// </summary>
|
||||
public ActionKind? FirstPageCategory { get; }
|
||||
|
||||
/// <summary>True when the operation always needs <c>{cursor}</c>.</summary>
|
||||
public bool RequiresCursor => RequiredValues.Contains(CaseValues.Cursor);
|
||||
|
||||
/// <summary>True when the operation takes <c>{cursor}</c> or <c>{cursor?}</c>.</summary>
|
||||
public bool TakesCursor => RequiresCursor || OptionalValues.Contains(CaseValues.Cursor);
|
||||
|
||||
/// <summary>
|
||||
/// The category <paramref name="request"/> counts in: <see cref="FirstPageCategory"/> for a first page (no cursor)
|
||||
/// when the operation has one, otherwise <see cref="Category"/>.
|
||||
/// </summary>
|
||||
public ActionKind CategoryFor(SiteRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
return FirstPageCategory is { } first && !request.Values.ContainsKey(CaseValues.Cursor) ? first : Category;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// False when the shapes do not tell everything the request needs (a variable whose name the probe removed, a
|
||||
/// value the shapes do not show, a header or field whose source is still <see cref="ValueSourceKind.Pending"/>):
|
||||
@@ -317,6 +431,7 @@ public sealed partial class RequestCatalog
|
||||
}.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
private readonly FrozenDictionary<string, SiteOperation> _byName;
|
||||
private readonly FrozenDictionary<RequestRole, SiteOperation> _byRole;
|
||||
|
||||
private RequestCatalog(string site, IReadOnlyList<SiteOperation> operations, string? source)
|
||||
{
|
||||
@@ -324,6 +439,7 @@ public sealed partial class RequestCatalog
|
||||
Operations = operations;
|
||||
Source = source ?? $"richieste.{site}.json";
|
||||
_byName = operations.ToFrozenDictionary(o => o.Name, StringComparer.Ordinal);
|
||||
_byRole = operations.SelectMany(o => o.Roles.Select(r => (Role: r, Operation: o))).ToFrozenDictionary(x => x.Role, x => x.Operation);
|
||||
}
|
||||
|
||||
/// <summary>The site name of the file (<c>instagram</c>, <c>prova</c>).</summary>
|
||||
@@ -341,6 +457,17 @@ public sealed partial class RequestCatalog
|
||||
public bool TryGet(string name, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out SiteOperation? operation) =>
|
||||
_byName.TryGetValue(name, out operation);
|
||||
|
||||
/// <summary>
|
||||
/// The operation that plays <paramref name="role"/>, when it can be asked: null when no operation holds the role,
|
||||
/// or when the one that holds it is not configured. A role on an operation that is not configured does not exist
|
||||
/// for the recipes: on Instagram, where nothing is configured yet, every recipe stays as it was.
|
||||
/// </summary>
|
||||
public SiteOperation? ForRole(RequestRole role) =>
|
||||
_byRole.TryGetValue(role, out var operation) && operation.IsConfigured && operation.PendingValues.Count == 0 ? operation : null;
|
||||
|
||||
/// <summary>The operation that holds <paramref name="role"/>, configured or not (documentation and tests only).</summary>
|
||||
public SiteOperation? HolderOf(RequestRole role) => _byRole.GetValueOrDefault(role);
|
||||
|
||||
/// <summary>The Instagram catalog (embedded <c>richieste.instagram.json</c>).</summary>
|
||||
public static RequestCatalog LoadInstagram() => LoadEmbedded("richieste.instagram.json");
|
||||
|
||||
@@ -381,6 +508,7 @@ public sealed partial class RequestCatalog
|
||||
|
||||
var operations = new List<SiteOperation>(file.Operations.Count);
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
var roleHolders = new Dictionary<RequestRole, string>();
|
||||
for (var i = 0; i < file.Operations.Count; i++)
|
||||
{
|
||||
var dto = file.Operations[i] ?? throw new InvalidDataException($"{name}, operazione {(i + 1).ToString(CultureInfo.InvariantCulture)}: voce vuota.");
|
||||
@@ -390,6 +518,14 @@ public sealed partial class RequestCatalog
|
||||
throw new InvalidDataException($"{name}: l'operazione «{operation.Name}» compare due volte.");
|
||||
}
|
||||
|
||||
foreach (var role in operation.Roles)
|
||||
{
|
||||
if (!roleHolders.TryAdd(role, operation.Name))
|
||||
{
|
||||
throw new InvalidDataException($"{name}: il ruolo «{RequestRoles.Name(role)}» è sia di «{roleHolders[role]}» sia di «{operation.Name}»: un ruolo appartiene a una sola operazione.");
|
||||
}
|
||||
}
|
||||
|
||||
operations.Add(operation);
|
||||
}
|
||||
|
||||
@@ -676,11 +812,59 @@ public sealed partial class RequestCatalog
|
||||
throw new InvalidDataException($"{where}: un'operazione non configurata dice perché («reason»).");
|
||||
}
|
||||
|
||||
var roles = Roles(dto.Roles, category, required, optional, where);
|
||||
ActionKind? firstPageCategory = null;
|
||||
if (dto.FirstPageCategory is not null)
|
||||
{
|
||||
if (category != ActionKind.BackfillPage)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «firstPageCategory» si scrive solo per un'operazione della categoria «storico».");
|
||||
}
|
||||
|
||||
firstPageCategory = ParseCategory(dto.FirstPageCategory, where);
|
||||
if (firstPageCategory != ActionKind.ProfileOpen)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «firstPageCategory» ammette solo «profilo» (la prima pagina della griglia arriva con il profilo).");
|
||||
}
|
||||
}
|
||||
|
||||
return new SiteOperation(
|
||||
name, kind, method!, path, category, configured, reason, parameters.ToFrozenDictionary(StringComparer.Ordinal),
|
||||
headers.ToFrozenDictionary(StringComparer.Ordinal), body.ToFrozenDictionary(StringComparer.Ordinal), variables,
|
||||
rootFields, sample, required.ToFrozenSet(StringComparer.Ordinal), optional.ToFrozenSet(StringComparer.Ordinal),
|
||||
[.. parameters.Keys], [.. headers.Keys], [.. body.Keys]);
|
||||
[.. parameters.Keys], [.. headers.Keys], [.. body.Keys], roles, firstPageCategory);
|
||||
}
|
||||
|
||||
/// <summary>The roles of an operation, checked against its category and its cursor.</summary>
|
||||
private static FrozenSet<RequestRole> Roles(List<string?>? names, ActionKind category, SortedSet<string> required, SortedSet<string> optional, string where)
|
||||
{
|
||||
var roles = new HashSet<RequestRole>();
|
||||
foreach (var text in names ?? [])
|
||||
{
|
||||
if (RequestRoles.Parse(text) is not { } role)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: ruolo «{text}» sconosciuto (ammessi: profile, posts, posts-next, highlights, tagged, tagged-next, reels, reels-next, stories, highlight, highlight-next, post, following, following-next).");
|
||||
}
|
||||
|
||||
if (category == ActionKind.ProfileSearch)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: una ricerca non ha ruoli nelle ricette.");
|
||||
}
|
||||
|
||||
if (RequestRoles.IsNext(role) && !required.Contains(CaseValues.Cursor) && !optional.Contains(CaseValues.Cursor))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: il ruolo «{RequestRoles.Name(role)}» va da una pagina alla successiva e vuole un'operazione con «{{cursor}}» o «{{cursor?}}».");
|
||||
}
|
||||
|
||||
if (!RequestRoles.IsNext(role) && required.Contains(CaseValues.Cursor))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: il ruolo «{RequestRoles.Name(role)}» chiede la prima pagina, senza cursore, e l'operazione vuole sempre «{{cursor}}».");
|
||||
}
|
||||
|
||||
roles.Add(role);
|
||||
}
|
||||
|
||||
return roles.ToFrozenSet();
|
||||
}
|
||||
|
||||
private static Dictionary<string, ValueSource> Sources(Dictionary<string, string?>? entries, string where, string what, bool isBody)
|
||||
@@ -880,6 +1064,10 @@ internal sealed class OperationDto
|
||||
public List<string>? Shapes { get; set; }
|
||||
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<string?>? Roles { get; set; }
|
||||
|
||||
public string? FirstPageCategory { get; set; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
|
||||
@@ -188,6 +188,13 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
|
||||
public Signal? ObserveSessionCookie(bool present) =>
|
||||
present ? null : Raise(SignalLevel.Disconnect, SignalRules.SessionCookieMissingCode, null);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public Signal? Report(Signal signal)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(signal);
|
||||
return Raise(signal.Level, signal.Code, signal.Url);
|
||||
}
|
||||
|
||||
private bool UserIsOnPage() => UserOwnsPage?.Invoke() == true;
|
||||
|
||||
private Signal? Raise(SignalLevel level, string code, string? url)
|
||||
|
||||
@@ -89,6 +89,7 @@
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "profilo",
|
||||
"roles": ["profile"],
|
||||
"configured": false,
|
||||
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9); la variabile senza nome è un vero/falso di valore non noto",
|
||||
"headers": {
|
||||
@@ -165,6 +166,8 @@
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "storico",
|
||||
"roles": ["posts"],
|
||||
"firstPageCategory": "profilo",
|
||||
"configured": false,
|
||||
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9)",
|
||||
"headers": {
|
||||
@@ -248,6 +251,7 @@
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "storico",
|
||||
"roles": ["reels"],
|
||||
"configured": false,
|
||||
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
|
||||
"headers": {
|
||||
@@ -326,6 +330,7 @@
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "storico",
|
||||
"roles": ["tagged"],
|
||||
"configured": false,
|
||||
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
|
||||
"headers": {
|
||||
@@ -401,6 +406,7 @@
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "profilo",
|
||||
"roles": ["highlights"],
|
||||
"configured": false,
|
||||
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
|
||||
"headers": {
|
||||
@@ -473,6 +479,7 @@
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "storia",
|
||||
"roles": ["stories"],
|
||||
"configured": false,
|
||||
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9)",
|
||||
"headers": {
|
||||
@@ -550,6 +557,7 @@
|
||||
"method": "POST",
|
||||
"path": "/graphql/query",
|
||||
"category": "storia",
|
||||
"roles": ["highlight"],
|
||||
"configured": false,
|
||||
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9)",
|
||||
"headers": {
|
||||
@@ -630,6 +638,7 @@
|
||||
"method": "POST",
|
||||
"path": "/graphql/query",
|
||||
"category": "storia",
|
||||
"roles": ["highlight-next"],
|
||||
"configured": false,
|
||||
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9); anche il valore di first non è noto (un numero che cambia)",
|
||||
"headers": {
|
||||
@@ -715,6 +724,7 @@
|
||||
"method": "GET",
|
||||
"path": "/api/v1/media/{media_id}/info/",
|
||||
"category": "post",
|
||||
"roles": ["post"],
|
||||
"configured": false,
|
||||
"reason": "il percorso è noto, ma intestazioni della pagina e del browser (come referer, sec-ch-ua e quella con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
|
||||
"headers": {
|
||||
|
||||
@@ -66,6 +66,7 @@
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "profilo",
|
||||
"roles": ["profile", "posts", "highlights"],
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:*/*",
|
||||
@@ -104,6 +105,7 @@
|
||||
"method": "GET",
|
||||
"path": "/api/dati/profilo/{username}/altri",
|
||||
"category": "storico",
|
||||
"roles": ["posts-next"],
|
||||
"configured": true,
|
||||
"parameters": {
|
||||
"dopo": "{cursor}",
|
||||
@@ -128,6 +130,7 @@
|
||||
"method": "GET",
|
||||
"path": "/api/dati/profilo/{username}",
|
||||
"category": "storico",
|
||||
"roles": ["tagged"],
|
||||
"configured": true,
|
||||
"parameters": {
|
||||
"scheda": "constant:taggati"
|
||||
@@ -149,8 +152,8 @@
|
||||
"method": "GET",
|
||||
"path": "/api/dati/profilo/{username}",
|
||||
"category": "storico",
|
||||
"configured": false,
|
||||
"reason": "manca il campione ripulito della risposta in tests/Febe.Tests/campioni/prova",
|
||||
"roles": ["reels"],
|
||||
"configured": true,
|
||||
"parameters": {
|
||||
"scheda": "constant:reel"
|
||||
},
|
||||
@@ -159,7 +162,12 @@
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken"
|
||||
}
|
||||
},
|
||||
"rootFields": [
|
||||
"contenuti"
|
||||
],
|
||||
"sample": "000012-reel",
|
||||
"note": "Nessuna operazione per le pagine successive: i reel di ogni account del sito di prova stanno in una pagina (12)."
|
||||
},
|
||||
{
|
||||
"name": "post",
|
||||
@@ -167,6 +175,7 @@
|
||||
"method": "GET",
|
||||
"path": "/api/dati/post/{code}",
|
||||
"category": "post",
|
||||
"roles": ["post"],
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
@@ -185,6 +194,7 @@
|
||||
"method": "GET",
|
||||
"path": "/api/dati/storie/{username}",
|
||||
"category": "storia",
|
||||
"roles": ["stories"],
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
@@ -203,6 +213,7 @@
|
||||
"method": "GET",
|
||||
"path": "/api/dati/evidenza/{highlight_id}",
|
||||
"category": "storia",
|
||||
"roles": ["highlight"],
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
@@ -221,6 +232,7 @@
|
||||
"method": "GET",
|
||||
"path": "/api/dati/seguiti",
|
||||
"category": "seguiti",
|
||||
"roles": ["following", "following-next"],
|
||||
"configured": true,
|
||||
"parameters": {
|
||||
"dopo": "{cursor?}"
|
||||
|
||||
@@ -128,6 +128,13 @@ public interface IRecipeRunner
|
||||
/// would only end in <see cref="RecipeStatus.NotConfigured"/>.
|
||||
/// </summary>
|
||||
string? NotConfiguredReason(RecipeKind kind) => null;
|
||||
|
||||
/// <summary>
|
||||
/// The budget category the first action of <paramref name="kind"/> takes on the route this runner gives it (the
|
||||
/// engine skips the recipe when that budget is exhausted, and marks it exhausted after a refusal). By default the
|
||||
/// category of the recipe by the pages (<see cref="CheckPolicy.CategoryOf"/>).
|
||||
/// </summary>
|
||||
ActionKind FirstCategory(RecipeKind kind) => CheckPolicy.CategoryOf(kind);
|
||||
}
|
||||
|
||||
/// <summary>Daily byte budget for CDN downloads (category «dati scaricati», spec §7.4).</summary>
|
||||
|
||||
@@ -835,8 +835,10 @@ internal sealed class SessionComposer
|
||||
return null;
|
||||
}
|
||||
|
||||
var category = CheckPolicy.CategoryOf(request.Kind);
|
||||
if (state.Exhausted.Contains(category))
|
||||
// By requests a recipe can still go back to the pages for one run (a value missing, a next page without a
|
||||
// request), and its first action is then that of the pages: both budgets must have room.
|
||||
var category = _runner.FirstCategory(request.Kind);
|
||||
if (state.Exhausted.Contains(category) || state.Exhausted.Contains(CheckPolicy.CategoryOf(request.Kind)))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
@@ -1006,10 +1008,19 @@ internal sealed class SessionComposer
|
||||
await RequeueAsync(task, "Rimandata: tetto raggiunto", now).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var recheck = await _s.Governor.EvaluateBudgetAsync(CheckPolicy.CategoryOf(kind), request.AccountId, ct).ConfigureAwait(false);
|
||||
// The refusal may have come on the route of the requests or, gone back to them, of the pages.
|
||||
var first = _runner.FirstCategory(kind);
|
||||
var pages = CheckPolicy.CategoryOf(kind);
|
||||
if (pages != first
|
||||
&& (await _s.Governor.EvaluateBudgetAsync(pages, request.AccountId, ct).ConfigureAwait(false)).Reason is DenialReason.HourlyBudgetReached or DenialReason.DailyBudgetReached)
|
||||
{
|
||||
state.Exhausted.Add(pages);
|
||||
}
|
||||
|
||||
var recheck = await _s.Governor.EvaluateBudgetAsync(first, request.AccountId, ct).ConfigureAwait(false);
|
||||
if (recheck.Reason is DenialReason.HourlyBudgetReached or DenialReason.DailyBudgetReached)
|
||||
{
|
||||
state.Exhausted.Add(CheckPolicy.CategoryOf(kind));
|
||||
state.Exhausted.Add(first);
|
||||
}
|
||||
else if (recheck.Reason is DenialReason.BreakerOpen or DenialReason.OutsideActiveWindow or DenialReason.Paused or DenialReason.UserIsDriving)
|
||||
{
|
||||
|
||||
@@ -23,6 +23,9 @@ public sealed record SimulationOptions
|
||||
|
||||
public SimulatedWorldOptions? World { get; init; }
|
||||
|
||||
/// <summary>Whether the simulated recipes go by the pages or by requests (<c>--raccolta</c>); it wins over <see cref="World"/>.</summary>
|
||||
public SimulatedCollection Collection { get; init; } = SimulatedCollection.Pages;
|
||||
|
||||
public EngineOptions? Engine { get; init; }
|
||||
|
||||
/// <summary>Full engine settings (e.g. a «Su misura» profile); when null, <see cref="Profile"/> with the other defaults.</summary>
|
||||
@@ -61,7 +64,7 @@ public static class EngineSimulation
|
||||
var clock = new VirtualClock(start, zone);
|
||||
await EngineSettingsStore.SaveAsync(storage.Settings, options.Settings ?? new EngineSettings { ProfileKind = options.Profile }, ct).ConfigureAwait(false);
|
||||
var services = await EngineServices.CreateAsync(storage, clock, new SeededRandom(options.Seed), options.Engine, ct: ct).ConfigureAwait(false);
|
||||
var worldOptions = options.World ?? new SimulatedWorldOptions { Seed = options.Seed };
|
||||
var worldOptions = (options.World ?? new SimulatedWorldOptions { Seed = options.Seed }) with { Collection = options.Collection };
|
||||
var world = new SimulatedWorld(storage, services.Governor, services.Governor, services.Breaker, clock, worldOptions);
|
||||
await world.InitializeAsync(start, end, services.Runtime.Profile, ct).ConfigureAwait(false);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Pacing;
|
||||
@@ -7,9 +8,26 @@ using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Simulation;
|
||||
|
||||
/// <summary>How the simulated recipes read the site (issue #36, S3).</summary>
|
||||
public enum SimulatedCollection
|
||||
{
|
||||
/// <summary>By the pages of the browser: one StoryView per story shown, the profile opened for a profile not followed.</summary>
|
||||
Pages,
|
||||
|
||||
/// <summary>
|
||||
/// By the requests of the site client: one StoryView per request of the stories of an account (all of them in one
|
||||
/// answer), no profile opened first, the waits of <see cref="RequestTimings"/> instead of the
|
||||
/// gestures.
|
||||
/// </summary>
|
||||
Requests,
|
||||
}
|
||||
|
||||
/// <summary>The fake world of the simulation (spec §14.3).</summary>
|
||||
public sealed record SimulatedWorldOptions
|
||||
{
|
||||
/// <summary>Whether the simulated recipes go by the pages or by requests (<c>--raccolta</c>).</summary>
|
||||
public SimulatedCollection Collection { get; init; } = SimulatedCollection.Pages;
|
||||
|
||||
public int FollowedAccounts { get; init; } = 25;
|
||||
|
||||
public int NotFollowedAccounts { get; init; } = 15;
|
||||
@@ -116,10 +134,15 @@ public sealed class SimulatedWorld : IRecipeRunner
|
||||
|
||||
public WorldStats Stats { get; } = new();
|
||||
|
||||
/// <summary>Whether the recipes of this world go by the pages or by requests.</summary>
|
||||
public SimulatedCollection Collection => _options.Collection;
|
||||
|
||||
public IReadOnlyList<SimAccount> Accounts => _accounts;
|
||||
|
||||
private double Pace => GesturePaceFactors.For(_options.Pace);
|
||||
|
||||
private bool ByRequests => _options.Collection == SimulatedCollection.Requests;
|
||||
|
||||
/// <summary>Creates the accounts in the database and the publications of the period [start, end).</summary>
|
||||
public async Task InitializeAsync(DateTimeOffset start, DateTimeOffset end, CautionProfile profile, CancellationToken ct = default)
|
||||
{
|
||||
@@ -335,22 +358,66 @@ public sealed class SimulatedWorld : IRecipeRunner
|
||||
}
|
||||
|
||||
account.LastProfileOpen = _clock.Now;
|
||||
await WaitAsync(session, 1, 6, 2.2, ct).ConfigureAwait(false);
|
||||
var bursts = _random.CountBetween(1, 3);
|
||||
for (var b = 0; b < bursts; b++)
|
||||
var counted = 1;
|
||||
if (ByRequests)
|
||||
{
|
||||
await WaitAsync(session, 0.4, 4, 1.1, ct).ConfigureAwait(false);
|
||||
// The cost of Instagram's split operations, the conservative case (the test site answers all in one): the
|
||||
// profile, then the first page of posts, each one ProfileOpen.
|
||||
await RequestGapAsync(session, ct).ConfigureAwait(false);
|
||||
var posts = await AskAsync(ActionKind.ProfileOpen, account.Id, ct).ConfigureAwait(false);
|
||||
if (!posts.Granted)
|
||||
{
|
||||
return Denied(counted, 0);
|
||||
}
|
||||
|
||||
counted++;
|
||||
if (posts.Throttled)
|
||||
{
|
||||
return Signal(counted, 0);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
await WaitAsync(session, 1, 6, 2.2, ct).ConfigureAwait(false);
|
||||
var bursts = _random.CountBetween(1, 3);
|
||||
for (var b = 0; b < bursts; b++)
|
||||
{
|
||||
await WaitAsync(session, 0.4, 4, 1.1, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var now = _clock.Now;
|
||||
var firstPage = account.Posts.Where(p => p.PublishedAt <= now).OrderByDescending(p => p.PublishedAt).Take(PostsPerPage);
|
||||
var fresh = firstPage.Where(p => p.DiscoveredAt is null).ToList();
|
||||
await StorePostsAsync(account, fresh, now, history: false, ct).ConfigureAwait(false);
|
||||
return new RecipeOutcome(RecipeStatus.Completed, 1, fresh.Count);
|
||||
if (ByRequests && (account.LastTrayAt is not { } tray || now - tray >= RecipeOptions.DefaultHighlightsTrayInterval))
|
||||
{
|
||||
// The list of collections, at most once a day per account, after the first page is saved: refused, it waits
|
||||
// for the next check. The waits come only between two requests, as in the recipe.
|
||||
await RequestGapAsync(session, ct).ConfigureAwait(false);
|
||||
var listed = await AskAsync(ActionKind.ProfileOpen, account.Id, ct).ConfigureAwait(false);
|
||||
if (listed.Granted)
|
||||
{
|
||||
counted++;
|
||||
if (listed.Throttled)
|
||||
{
|
||||
return Signal(counted, fresh.Count);
|
||||
}
|
||||
|
||||
account.LastTrayAt = _clock.Now;
|
||||
}
|
||||
}
|
||||
|
||||
return new RecipeOutcome(RecipeStatus.Completed, counted, fresh.Count);
|
||||
}
|
||||
|
||||
private async Task<RecipeOutcome> StoriesAsync(SimAccount account, ISessionContext session, CancellationToken ct)
|
||||
{
|
||||
if (ByRequests)
|
||||
{
|
||||
return await StoriesByRequestAsync(account, session, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var counted = 0;
|
||||
var now = _clock.Now;
|
||||
if (!account.Followed && (account.LastProfileOpen is not { } opened || now - opened > TimeSpan.FromMinutes(2)))
|
||||
@@ -412,10 +479,65 @@ public sealed class SimulatedWorld : IRecipeRunner
|
||||
return new RecipeOutcome(RecipeStatus.Completed, counted, seen);
|
||||
}
|
||||
|
||||
/// <summary>The stories of an account by one request: one StoryView, every active story in the answer.</summary>
|
||||
private async Task<RecipeOutcome> StoriesByRequestAsync(SimAccount account, ISessionContext session, CancellationToken ct)
|
||||
{
|
||||
var permit = await AskAsync(ActionKind.StoryView, account.Id, ct).ConfigureAwait(false);
|
||||
if (!permit.Granted)
|
||||
{
|
||||
return Denied(0, 0);
|
||||
}
|
||||
|
||||
if (permit.Throttled)
|
||||
{
|
||||
return Signal(1, 0);
|
||||
}
|
||||
|
||||
await RequestGapAsync(session, ct).ConfigureAwait(false);
|
||||
var at = _clock.Now;
|
||||
var seen = 0;
|
||||
foreach (var story in account.Stories.Where(s => s.PublishedAt <= at && s.ExpiresAt > at && s.SeenAt is null).ToList())
|
||||
{
|
||||
story.SeenAt = at;
|
||||
Stats.StoryViews.Add((story.PublishedAt, at));
|
||||
await StoreStoryAsync(account, story, at, ct).ConfigureAwait(false);
|
||||
seen++;
|
||||
}
|
||||
|
||||
var day = LocalCalendar.Today(_clock.Now, _clock.LocalZone);
|
||||
Stats.StoryChecks[(account.Id, day)] = Stats.StoryChecks.GetValueOrDefault((account.Id, day)) + 1;
|
||||
return new RecipeOutcome(RecipeStatus.Completed, 1, seen);
|
||||
}
|
||||
|
||||
/// <summary>The wait after an answer of the site client (<see cref="RequestTimings.AfterAnswer"/>).</summary>
|
||||
private Task RequestGapAsync(ISessionContext session, CancellationToken ct) =>
|
||||
_clock.Delay(RequestTimings.AfterAnswer(_random, session.Mood * Pace), ct);
|
||||
|
||||
private async Task<RecipeOutcome> BackfillAsync(SimAccount account, int maxPages, ISessionContext session, CancellationToken ct)
|
||||
{
|
||||
var pages = 0;
|
||||
var stored = 0;
|
||||
var counted = 0;
|
||||
if (ByRequests && account.HistoryCursor == 0 && account.LastProfileOpen is null && account.History.Count > 0)
|
||||
{
|
||||
// No profile check stored a point yet: the first page of the grid is asked without a cursor, and counts as
|
||||
// the profile (firstPageCategory), not among the pages of the run.
|
||||
var first = await AskAsync(ActionKind.ProfileOpen, account.Id, ct).ConfigureAwait(false);
|
||||
if (!first.Granted)
|
||||
{
|
||||
return Denied(0, 0);
|
||||
}
|
||||
|
||||
counted++;
|
||||
if (first.Throttled)
|
||||
{
|
||||
return Signal(counted, 0);
|
||||
}
|
||||
|
||||
account.LastProfileOpen = _clock.Now;
|
||||
await RequestGapAsync(session, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
while (pages < maxPages && _clock.Now < session.PlannedEnd)
|
||||
{
|
||||
if (account.HistoryCursor >= account.History.Count)
|
||||
@@ -426,13 +548,13 @@ public sealed class SimulatedWorld : IRecipeRunner
|
||||
var permit = await AskAsync(ActionKind.BackfillPage, account.Id, ct).ConfigureAwait(false);
|
||||
if (!permit.Granted)
|
||||
{
|
||||
return pages > 0 ? new RecipeOutcome(RecipeStatus.Completed, pages, stored) : Denied(0, 0);
|
||||
return pages > 0 ? new RecipeOutcome(RecipeStatus.Completed, counted + pages, stored) : Denied(counted, 0);
|
||||
}
|
||||
|
||||
pages++;
|
||||
if (permit.Throttled)
|
||||
{
|
||||
return Signal(pages, stored);
|
||||
return Signal(counted + pages, stored);
|
||||
}
|
||||
|
||||
await WaitAsync(session, 2, 8, 3.5, ct).ConfigureAwait(false);
|
||||
@@ -449,7 +571,7 @@ public sealed class SimulatedWorld : IRecipeRunner
|
||||
Stats.BackfillFinishedAt = _clock.Now;
|
||||
}
|
||||
|
||||
return new RecipeOutcome(RecipeStatus.Completed, pages, stored) { BackfillFinished = finished };
|
||||
return new RecipeOutcome(RecipeStatus.Completed, counted + pages, stored) { BackfillFinished = finished };
|
||||
}
|
||||
|
||||
private async Task<RecipeOutcome> SimpleAsync(ActionKind kind, long? accountId, ISessionContext session, CancellationToken ct)
|
||||
@@ -660,6 +782,9 @@ public sealed class SimAccount(long id, string username, bool followed, int inde
|
||||
internal List<SimStory> Stories { get; } = [];
|
||||
|
||||
internal DateTimeOffset? LastProfileOpen { get; set; }
|
||||
|
||||
/// <summary>When the list of highlight collections was last asked by requests.</summary>
|
||||
internal DateTimeOffset? LastTrayAt { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class SimPost(string id, DateTimeOffset publishedAt, int files, bool hasVideo)
|
||||
|
||||
@@ -45,6 +45,9 @@ public sealed class SimulationReport
|
||||
|
||||
public required CautionProfileKind Profile { get; init; }
|
||||
|
||||
/// <summary>Whether the simulated recipes went by the pages or by requests.</summary>
|
||||
public SimulatedCollection Collection { get; init; }
|
||||
|
||||
public required int Seed { get; init; }
|
||||
|
||||
public required DateTimeOffset Start { get; init; }
|
||||
@@ -306,6 +309,7 @@ public sealed class SimulationReport
|
||||
return new SimulationReport
|
||||
{
|
||||
Profile = profile.Kind,
|
||||
Collection = world.Collection,
|
||||
Seed = options.Seed,
|
||||
Start = start,
|
||||
End = end,
|
||||
@@ -353,6 +357,7 @@ public sealed class SimulationReport
|
||||
var firstDay = LocalCalendar.Today(Start, Zone);
|
||||
var lastDay = LocalCalendar.Today(End - TimeSpan.FromTicks(1), Zone);
|
||||
b.AppendLine($"Simulazione del motore: {ItalianText.Count(Days.Count, "giorno", "giorni")} con il profilo «{ItalianText.Profile(Profile)}» (seme {Seed.ToString(CultureInfo.InvariantCulture)})");
|
||||
b.AppendLine(Collection == SimulatedCollection.Requests ? "Raccolta: per richieste" : "Raccolta: per pagine");
|
||||
b.AppendLine($"Periodo: dal {ItalianText.Day(firstDay)} alle {ItalianText.Clock(Start, Zone)} al {ItalianText.Day(lastDay)}, fuso {Zone.Id}");
|
||||
b.AppendLine($"Mondo finto: {ItalianText.Number(Accounts)} account ({ItalianText.Number(FollowedAccounts)} seguiti, {ItalianText.Number(Accounts - FollowedAccounts)} no), {ItalianText.Number(PublishedPosts)} post e {ItalianText.Number(PublishedStories)} storie pubblicati nel periodo, uno storico di {ItalianText.Number(BackfillPosts)} post");
|
||||
b.AppendLine("I tetti del profilo sono stime prudenti, non limiti ufficiali di Instagram.");
|
||||
|
||||
Reference in new issue
Block a user