Il client del sito ha bisogno della sessione del browser di Febe: ora la copia c'è, cifrata e dietro un interruttore, senza cambiare nulla di predefinito. - Opzione «raccolta» (pagine predefinita, richieste): solo con «richieste» e almeno un'operazione configurata si costruiscono sessione salvata, client del sito e copia. Con Instagram nulla cambia: le dieci operazioni restano non configurate (mancano __spin_*, __req, __s, __dyn, __csr e altri). - Cookie con dominio, percorso, solo-host, Secure, HttpOnly e scadenza, mandati solo dove il browser li manderebbe (RFC 6265). - Sezione «page» del catalogo: dove la pagina tiene ogni valore; nuovi campi rev, hs, hsi, dpr, ccg, comet_req, entry_nonce. Il caricatore rifiuta un'operazione configurata con un valore di sessione senza fonte nella pagina. - Dati/sessione/sessione.json: DPAPI su Windows, AES-256-GCM in Docker (chiave da FEBE_CHIAVE_SESSIONE o chiave.bin), scrittura atomica, file illeggibile = nessuna sessione. «Scollega» la cancella; chiave.bin resta. - Copia a «Ho finito» con Network.getCookies e una sola Runtime.evaluate in sola lettura, solo da una pagina del sito e finché dura il permesso di guida. - FEBE_PASSWORD e FEBE_CHIAVE_SESSIONE non passano a Chromium, Xvfb, ffmpeg. - Sito di prova: csrftoken, cookie limitato a /api/, registro di moduli suo. - Revisione su tre lenti: 11 punti confermati, tutti corretti. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
306 lines
13 KiB
C#
306 lines
13 KiB
C#
using Febe.Browser.Capture;
|
|
using Febe.Browser.Diagnostics;
|
|
using Febe.Browser.Download;
|
|
using Febe.Browser.Hosting;
|
|
using Febe.Browser.Targets;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Collection;
|
|
using Febe.Core.Collection.Diagnostics;
|
|
using Febe.Core.Collection.Downloads;
|
|
using Febe.Core.Collection.Readers;
|
|
using Febe.Core.Collection.Recipes;
|
|
using Febe.Core.Collection.Requests;
|
|
using Febe.Core.Collection.Search;
|
|
using Febe.Core.Domain;
|
|
using Febe.Core.Engine;
|
|
using Febe.Core.Library;
|
|
using Febe.Core.Storage;
|
|
|
|
namespace Febe.Browser.Recipes;
|
|
|
|
/// <summary>The site the pipeline works on: its name (configuration files), address, hosts and session cookie.</summary>
|
|
/// <param name="Name">«instagram» or «prova»: selects <c>bersagli.{Name}.json</c> and <c>lettori.{Name}.json</c>.</param>
|
|
/// <param name="BaseUrl">Address the recipes open pages under.</param>
|
|
/// <param name="Hosts">Site and CDN hosts.</param>
|
|
/// <param name="SessionCookie">Where the session cookie is checked (existence only).</param>
|
|
public sealed record CollectionSite(string Name, string BaseUrl, HostClassifier Hosts, SessionCookieOptions SessionCookie)
|
|
{
|
|
/// <summary>
|
|
/// Instagram. Its reader vocabulary is confirmed on real cleaned samples and its map has the pages seen in real
|
|
/// traffic, not yet the targets: a recipe that needs a target refuses to run and says why, without touching the site.
|
|
/// </summary>
|
|
public static CollectionSite Instagram { get; } = new("instagram", "https://www.instagram.com", HostClassifier.Instagram, SessionCookieOptions.Instagram);
|
|
|
|
/// <summary>The local test site (tools/Febe.SitoDiProva) on «127.0.0.1:port», with its CDN on another host.</summary>
|
|
public static CollectionSite TestSite(string siteHost, string cdnHost) =>
|
|
new("prova", $"http://{siteHost}", new HostClassifier([siteHost], [cdnHost]), new SessionCookieOptions("sessione_prova", $"http://{siteHost}/"));
|
|
|
|
/// <summary>The stop-signal rules of the site.</summary>
|
|
public string SignalsFile => Name == "prova" ? "segnali.prova.json" : "segnali.json";
|
|
}
|
|
|
|
/// <summary>What <see cref="CollectionPipeline.StartAsync"/> needs.</summary>
|
|
public sealed record CollectionPipelineOptions
|
|
{
|
|
public required ICdpSession Cdp { get; init; }
|
|
|
|
public required CollectionSite Site { get; init; }
|
|
|
|
public required IFebeStorage Storage { get; init; }
|
|
|
|
public required LibraryIngest Ingest { get; init; }
|
|
|
|
public required IGovernor Governor { get; init; }
|
|
|
|
/// <summary>Remaining budgets for the «at least ten stories» check; usually the Governor itself.</summary>
|
|
public IBudgetView? Budget { get; init; }
|
|
|
|
public required IDataBudget DataBudget { get; init; }
|
|
|
|
/// <summary>The circuit breaker: signals are reported to it, and recipes stop when it opens.</summary>
|
|
public required ICircuitBreaker Breaker { get; init; }
|
|
|
|
public required IClock Clock { get; init; }
|
|
|
|
public required IRandomSource Random { get; init; }
|
|
|
|
/// <summary>Temporary folder for downloads (under Dati).</summary>
|
|
public required string StagingFolder { get; init; }
|
|
|
|
/// <summary>
|
|
/// Folder with editable copies of the configuration (Dati, spec §8.2): <c>segnali.json</c>, <c>bersagli.*.json</c>,
|
|
/// <c>lettori.*.json</c>. Files missing there come from the copies embedded in Febe.Core.
|
|
/// </summary>
|
|
public string? ConfigFolder { get; init; }
|
|
|
|
public GesturePace Pace { get; init; } = GesturePace.Natural;
|
|
|
|
public RecipeOptions Recipes { get; init; } = new();
|
|
|
|
/// <summary>True while Alberto uses the browser: gestures are not performed.</summary>
|
|
public Func<bool>? UserIsDriving { get; init; }
|
|
|
|
/// <summary>
|
|
/// True while the page is Alberto's (he uses the browser and no engine session runs): what he opens is not a stop
|
|
/// signal (<see cref="SignalDetector.UserOwnsPage"/>). Null: always the engine's.
|
|
/// </summary>
|
|
public Func<bool>? UserOwnsPage { get; init; }
|
|
|
|
public IBrowserLog? Log { get; init; }
|
|
|
|
/// <summary>
|
|
/// The recorder of the diagnostic report (issue #39): it observes the responses of the page, the readers, the
|
|
/// recipes, the stop signals and the download queue. Null: nothing is recorded.
|
|
/// </summary>
|
|
public CollectionDiagnostics? Diagnostics { get; init; }
|
|
|
|
/// <summary>
|
|
/// The turns of the one page shared by the recipes and the profile search (issue #37). Null: no profile search
|
|
/// (the pipeline builds no search runner).
|
|
/// </summary>
|
|
public PageTurns? PageTurns { get; init; }
|
|
|
|
/// <summary>Times and bounds of the profile search.</summary>
|
|
public ProfileSearchOptions SearchOptions { get; init; } = ProfileSearchOptions.Default;
|
|
|
|
/// <summary>Where the photos of the search results are kept (memory). Null: the search fetches no photo.</summary>
|
|
public SearchPhotoCache? SearchPhotos { get; init; }
|
|
|
|
/// <summary>
|
|
/// The site client and its catalog (issue #36, S3): the recipes whose roles are all configured go by requests.
|
|
/// Null: every recipe goes by the browser. Since S4 production sets it only with the option «raccolta» on
|
|
/// «richieste» and a catalog with configured operations (never with Instagram while none is configured).
|
|
/// </summary>
|
|
public SiteRequestOptions? Requests { get; init; }
|
|
}
|
|
|
|
/// <summary>The site client of the pipeline and the catalog of its operations (issue #36, S3).</summary>
|
|
/// <param name="Requester">The site client: 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>
|
|
public sealed record SiteRequestOptions(ISiteRequester Requester, RequestCatalog Catalog);
|
|
|
|
/// <summary>
|
|
/// The collection pipeline put together (spec §6): response tap, stop signals, readers, page driver, recipe runner and
|
|
/// download queue, all on one browser page. Disposing it stops listening to the page.
|
|
/// </summary>
|
|
public sealed class CollectionPipeline : IAsyncDisposable
|
|
{
|
|
private readonly List<IDisposable> _subscriptions = [];
|
|
|
|
private CollectionPipeline(ResponseTap tap, SignalDetector signals, CaptureCollector capture, BrowserPageDriver driver, RecipeRunner runner, DownloadQueue downloads, SiteMap siteMap, TargetMap targets, ProfileSearchRunner? search, SearchPhotoQueue? searchPhotos)
|
|
{
|
|
Search = search;
|
|
SearchPhotos = searchPhotos;
|
|
Tap = tap;
|
|
Signals = signals;
|
|
Capture = capture;
|
|
Driver = driver;
|
|
Runner = runner;
|
|
Downloads = downloads;
|
|
SiteMap = siteMap;
|
|
Targets = targets;
|
|
}
|
|
|
|
public ResponseTap Tap { get; }
|
|
|
|
public SignalDetector Signals { get; }
|
|
|
|
public CaptureCollector Capture { get; }
|
|
|
|
public BrowserPageDriver Driver { get; }
|
|
|
|
/// <summary>The <see cref="IRecipeRunner"/> of the engine.</summary>
|
|
public RecipeRunner Runner { get; }
|
|
|
|
public DownloadQueue Downloads { get; }
|
|
|
|
/// <summary>The browser half of the profile search (issue #37); null without <see cref="CollectionPipelineOptions.PageTurns"/>.</summary>
|
|
public ProfileSearchRunner? Search { get; }
|
|
|
|
/// <summary>The photo queue of the profile search; null without a photo cache.</summary>
|
|
public SearchPhotoQueue? SearchPhotos { get; }
|
|
|
|
public SiteMap SiteMap { get; }
|
|
|
|
public TargetMap Targets { get; }
|
|
|
|
public ReaderVocabulary Vocabulary => Capture.Reader.Vocabulary;
|
|
|
|
public static async Task<CollectionPipeline> StartAsync(CollectionPipelineOptions options, CancellationToken ct = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(options);
|
|
string? Override(string file) => options.ConfigFolder is { } folder ? Path.Combine(folder, file) : null;
|
|
var site = options.Site;
|
|
var siteMap = SiteMap.LoadOrEmbedded(Override($"bersagli.{site.Name}.json"), $"bersagli.{site.Name}.json");
|
|
var targets = TargetMap.LoadOrEmbedded(Override($"bersagli.{site.Name}.json"), $"bersagli.{site.Name}.json");
|
|
var vocabulary = ReaderVocabulary.LoadOrEmbedded(Override($"lettori.{site.Name}.json"), $"lettori.{site.Name}.json");
|
|
var rulesFile = Override(site.SignalsFile);
|
|
var rules = rulesFile is not null && File.Exists(rulesFile) ? SignalRules.Load(rulesFile) : SignalRules.LoadEmbedded(site.SignalsFile);
|
|
|
|
var tap = new ResponseTap(options.Cdp, site.Hosts, options.Clock, options.Log);
|
|
var signals = new SignalDetector(rules, options.Breaker, options.Clock) { UserOwnsPage = options.UserOwnsPage };
|
|
var diagnostics = options.Diagnostics;
|
|
var capture = new CaptureCollector(new ShapeReader(vocabulary), options.Clock) { Diagnostics = diagnostics };
|
|
var driver = new BrowserPageDriver(options.Cdp, targets, site.Hosts, options.Clock, options.Random, new BrowserDriverOptions
|
|
{
|
|
SiteBaseUrl = site.BaseUrl,
|
|
Pace = options.Pace,
|
|
SessionCookie = site.SessionCookie,
|
|
UserIsDriving = options.UserIsDriving,
|
|
});
|
|
var runner = new RecipeRunner(new RecipeEnvironment
|
|
{
|
|
Driver = driver,
|
|
Capture = capture,
|
|
Governor = options.Governor,
|
|
Budget = options.Budget ?? options.Governor as IBudgetView,
|
|
Signals = signals,
|
|
Storage = options.Storage,
|
|
SiteMap = siteMap,
|
|
Clock = options.Clock,
|
|
Random = options.Random,
|
|
DataBudget = options.DataBudget,
|
|
Breaker = options.Breaker,
|
|
Options = options.Recipes,
|
|
Diagnostics = diagnostics,
|
|
PageTurns = options.PageTurns,
|
|
Requests = options.Requests is { } requests
|
|
? new SiteRequestEnvironment(
|
|
requests.Requester,
|
|
requests.Catalog,
|
|
new SiteAnswerSignals(rules, site.SessionCookie.CookieName),
|
|
options.Pace,
|
|
message => options.Log?.Write(BrowserLogLevel.Warning, message))
|
|
: null,
|
|
});
|
|
var fetcher = new BrowserFileFetcher(options.Cdp, site.Hosts, options.Log);
|
|
var downloads = new DownloadQueue(
|
|
options.Storage,
|
|
options.Ingest,
|
|
fetcher,
|
|
options.DataBudget,
|
|
options.Clock,
|
|
options.Random,
|
|
new DownloadOptions { StagingFolder = options.StagingFolder },
|
|
signals);
|
|
|
|
ProfileSearchRunner? search = null;
|
|
SearchPhotoQueue? searchPhotos = null;
|
|
if (options.PageTurns is { } turns)
|
|
{
|
|
search = new ProfileSearchRunner(
|
|
driver,
|
|
driver,
|
|
capture,
|
|
siteMap,
|
|
options.Governor,
|
|
signals,
|
|
options.Breaker,
|
|
options.Clock,
|
|
options.Random,
|
|
turns,
|
|
options.SearchOptions,
|
|
options.UserIsDriving,
|
|
diagnostics);
|
|
if (options.SearchPhotos is { } photos)
|
|
{
|
|
// Photos only while the page is on the site: from the rest page the browser may block the CDN (H7).
|
|
searchPhotos = new SearchPhotoQueue(
|
|
photos,
|
|
fetcher,
|
|
options.Governor,
|
|
options.DataBudget,
|
|
options.Breaker,
|
|
options.Clock,
|
|
options.Random,
|
|
options.SearchOptions,
|
|
signals,
|
|
() => turns.LastUser is not null)
|
|
{
|
|
Diagnostics = diagnostics,
|
|
};
|
|
}
|
|
}
|
|
|
|
var pipeline = new CollectionPipeline(tap, signals, capture, driver, runner, downloads, siteMap, targets, search, searchPhotos);
|
|
pipeline._subscriptions.Add(tap.AddObserver(signals));
|
|
pipeline._subscriptions.Add(tap.AddConsumer(signals));
|
|
pipeline._subscriptions.Add(tap.AddObserver(capture));
|
|
pipeline._subscriptions.Add(tap.AddConsumer(capture));
|
|
if (diagnostics is not null)
|
|
{
|
|
diagnostics.SiteMap = siteMap;
|
|
pipeline._subscriptions.Add(tap.AddObserver(diagnostics));
|
|
EventHandler<Signal> signalRaised = (_, signal) => diagnostics.SignalRaised(signal);
|
|
signals.SignalRaised += signalRaised;
|
|
pipeline._subscriptions.Add(new Unsubscribe(() => signals.SignalRaised -= signalRaised));
|
|
EventHandler<DownloadProgress> progress = (_, step) => diagnostics.DownloadSettled(step);
|
|
downloads.Progress += progress;
|
|
pipeline._subscriptions.Add(new Unsubscribe(() => downloads.Progress -= progress));
|
|
}
|
|
|
|
await tap.StartAsync(ct).ConfigureAwait(false);
|
|
return pipeline;
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
foreach (var subscription in _subscriptions)
|
|
{
|
|
subscription.Dispose();
|
|
}
|
|
|
|
if (SearchPhotos is not null)
|
|
{
|
|
await SearchPhotos.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
await Tap.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
private sealed class Unsubscribe(Action action) : IDisposable
|
|
{
|
|
public void Dispose() => action();
|
|
}
|
|
}
|