Giunto per le richieste dirette, senza cambiare comportamento (#36, S1)
Le risposte catturate dal browser e quelle che il client del sito chiederà devono arrivare ai lettori e ai segnali nello stesso modo: la consegna passa in ResponseDelivery (Core), che ResponseTap usa con gli stessi conteggi e messaggi. Arrivano i contratti SiteRequest, SiteAnswer e ISiteRequester con SiteRequestGuard (un permesso concesso, della categoria giusta, per una sola richiesta) e RequestCatalog, che legge richieste.<sito>.json e tiene nel codice i divieti: nomi con Mutation, chat, telemetria, /ajax/, /ws/, percorsi con segmenti strani. Nessun doc_id nel repository; nessuna operazione di Instagram è ancora configurata perché le forme della sonda non dicono da dove vengano alcuni campi (tappa S4). ScriptedRequester risponde dai campioni ripuliti per le prove. Nulla di nuovo è collegato al motore. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d4675a5e21
commit
76dd1b6032
15 files changed
+3488
-68
No files matched your search
@@ -0,0 +1,126 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Core.Collection.Requests;
|
||||
|
||||
/// <summary>
|
||||
/// Asks the site for one operation of the catalog (issue #36, spec §6.0) and returns its answer. The only way the
|
||||
/// engine talks to the site without the browser: the HTTP implementation (tappa S2) is the one class of Febe that
|
||||
/// contacts <c>www.instagram.com</c> (rule 3), the test double answers from the cleaned samples.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <list type="bullet">
|
||||
/// <item>Every call needs a <see cref="Permit"/> the Governor granted for that very request (rule 8, §7.4): a permit per
|
||||
/// request, never one for several. An implementation refuses, with <see cref="SiteRequestRefusedException"/> and before
|
||||
/// anything leaves, a permit that is missing, not granted or already presented once (<see cref="SpentPermits"/>), a
|
||||
/// permit of another category than the operation's (<see cref="SiteOperation.Category"/>), an operation that is not in
|
||||
/// the catalog, not configured or with a header or field still <see cref="ValueSourceKind.Pending"/>, and values that
|
||||
/// do not match the operation's placeholders or would change its path. <see cref="SiteRequestGuard"/> does all of
|
||||
/// these checks.</item>
|
||||
/// <item>One request at a time: an implementation never sends two together and makes a second call wait (or refuse)
|
||||
/// until the first has its answer; the minimum spacing of §7.7 is the Governor's.</item>
|
||||
/// <item>Only reads: the catalog refuses writes when it loads (<see cref="RequestCatalog"/>).</item>
|
||||
/// <item>Redirects are never followed: a 3xx comes back as a <see cref="SiteAnswer"/> with <see cref="SiteAnswer.IsRedirect"/>.</item>
|
||||
/// <item>Logs name only the operation or the shape of the path and the status (rule 10).</item>
|
||||
/// </list>
|
||||
/// Cancellation throws <see cref="OperationCanceledException"/>. The answer goes to the readers through
|
||||
/// <see cref="ResponseDelivery"/>, like the captured ones.
|
||||
/// </remarks>
|
||||
public interface ISiteRequester
|
||||
{
|
||||
Task<SiteAnswer> SendAsync(SiteRequest request, Permit permit, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A request that must not leave: no granted permit, a permit already used, another category, an operation outside
|
||||
/// the catalog or not configured, values that do not match. The message is in Italian and names only the operation and
|
||||
/// value names.
|
||||
/// </summary>
|
||||
public sealed class SiteRequestRefusedException : InvalidOperationException
|
||||
{
|
||||
public SiteRequestRefusedException()
|
||||
{
|
||||
}
|
||||
|
||||
public SiteRequestRefusedException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public SiteRequestRefusedException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The permits a site client was already shown (rule 8, §7.4: a permit per request). By reference, not by value: two
|
||||
/// permits the Governor granted one after the other are two, even when their fields are equal. Holds them weakly, so a
|
||||
/// long run does not keep them alive.
|
||||
/// </summary>
|
||||
public sealed class SpentPermits
|
||||
{
|
||||
private static readonly object Marker = new();
|
||||
private readonly ConditionalWeakTable<Permit, object> _spent = new();
|
||||
|
||||
/// <summary>Marks <paramref name="permit"/> as used; false when it was used before.</summary>
|
||||
public bool TrySpend(Permit permit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(permit);
|
||||
return _spent.TryAdd(permit, Marker);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The checks every <see cref="ISiteRequester"/> makes before a request leaves.</summary>
|
||||
public static class SiteRequestGuard
|
||||
{
|
||||
/// <summary>
|
||||
/// The catalog operation <paramref name="request"/> asks for, when it may leave with <paramref name="permit"/>. A
|
||||
/// granted permit is spent as soon as it is shown, also when the request is then refused: the Governor has already
|
||||
/// counted it.
|
||||
/// </summary>
|
||||
/// <exception cref="SiteRequestRefusedException">It must not leave (see <see cref="ISiteRequester"/>).</exception>
|
||||
public static SiteOperation Check(RequestCatalog catalog, SiteRequest request, Permit? permit, SpentPermits spent)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(catalog);
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(spent);
|
||||
if (permit is null || !permit.Granted)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: il Governatore non ha dato il permesso.");
|
||||
}
|
||||
|
||||
if (!spent.TrySpend(permit))
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: il permesso è già stato usato (un permesso per richiesta).");
|
||||
}
|
||||
|
||||
if (!catalog.TryGet(request.Operation, out var operation))
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: l'operazione non è in {catalog.Source}.");
|
||||
}
|
||||
|
||||
if (!operation.IsConfigured)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: l'operazione non è configurata ({operation.NotConfiguredReason}).");
|
||||
}
|
||||
|
||||
// The catalog never loads a configured operation with pending sources; checked again so no path relies on it.
|
||||
if (operation.PendingValues.Count > 0)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: intestazioni o campi senza una fonte stabilita.");
|
||||
}
|
||||
|
||||
if (permit.Kind != operation.Category)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: il permesso è per {permit.Kind}, l'operazione conta come {operation.Category}.");
|
||||
}
|
||||
|
||||
if (operation.CheckValues(request) is { } problem)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: {problem}");
|
||||
}
|
||||
|
||||
return operation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,869 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Core.Collection.Requests;
|
||||
|
||||
/// <summary>Whether an operation is a GraphQL query of the site or a plain address.</summary>
|
||||
public enum OperationKind
|
||||
{
|
||||
/// <summary>A GraphQL query: POST of a form to one of the GraphQL entry points, named by its friendly name.</summary>
|
||||
GraphQl,
|
||||
|
||||
/// <summary>A plain address read with GET (e.g. <c>/api/v1/media/{numero}/info/</c>).</summary>
|
||||
Rest,
|
||||
}
|
||||
|
||||
/// <summary>Where the value of a header or of a form field comes from.</summary>
|
||||
public enum ValueSourceKind
|
||||
{
|
||||
/// <summary>A constant, as the request shapes show it (<c>x-asbd-id: 359341</c>).</summary>
|
||||
Constant,
|
||||
|
||||
/// <summary>The value of a cookie of the saved session (<c>x-csrftoken</c> is the cookie <c>csrftoken</c>).</summary>
|
||||
Cookie,
|
||||
|
||||
/// <summary>A value the saved session holds (§6.0): user agent, tokens, account, application, claim, doc_id.</summary>
|
||||
Session,
|
||||
|
||||
/// <summary>The name of the operation (<c>x-fb-friendly-name</c>, <c>fb_api_req_friendly_name</c>).</summary>
|
||||
Operation,
|
||||
|
||||
/// <summary>The variables of the operation, filled with the values of the case (form field <c>variables</c>).</summary>
|
||||
Variables,
|
||||
|
||||
/// <summary>Computed by the HTTP stack (<c>content-length</c>).</summary>
|
||||
Computed,
|
||||
|
||||
/// <summary>
|
||||
/// Not settled yet: the request shapes show the name but not where its value comes from (a value of the page, of
|
||||
/// the browser, or a name the probe removed). The site client cannot send it until it is settled (tappa S4).
|
||||
/// </summary>
|
||||
Pending,
|
||||
}
|
||||
|
||||
/// <summary>Where one header or form field of an operation takes its value from.</summary>
|
||||
/// <param name="Kind">The kind of source.</param>
|
||||
/// <param name="Argument">The constant, the cookie name or the session field; null for the other kinds.</param>
|
||||
public sealed record ValueSource(ValueSourceKind Kind, string? Argument)
|
||||
{
|
||||
/// <summary>The session fields a header or field may take (§6.0, what «Ho finito» copies).</summary>
|
||||
public static IReadOnlySet<string> SessionFields { get; } = new[]
|
||||
{
|
||||
"user_agent", "lsd", "fb_dtsg", "app_id", "claim", "account_id", "doc_id",
|
||||
}.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The text form of the catalog file: <c>constant:…</c>, <c>cookie:…</c>, <c>session:…</c>, <c>operation</c>, <c>variables</c>, <c>computed</c>, <c>pending</c>.</summary>
|
||||
public override string ToString() => Kind switch
|
||||
{
|
||||
ValueSourceKind.Constant => $"constant:{Argument}",
|
||||
ValueSourceKind.Cookie => $"cookie:{Argument}",
|
||||
ValueSourceKind.Session => $"session:{Argument}",
|
||||
ValueSourceKind.Operation => "operation",
|
||||
ValueSourceKind.Variables => "variables",
|
||||
ValueSourceKind.Computed => "computed",
|
||||
_ => "pending",
|
||||
};
|
||||
}
|
||||
|
||||
/// <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
|
||||
/// (rule 9). It holds no value of a session: the <c>doc_id</c> of a GraphQL query, the tokens and the account are read
|
||||
/// from the page at login (tappa S4) and named here only by their source.
|
||||
/// </summary>
|
||||
public sealed partial class SiteOperation
|
||||
{
|
||||
internal SiteOperation(
|
||||
string name,
|
||||
OperationKind kind,
|
||||
string method,
|
||||
string path,
|
||||
ActionKind category,
|
||||
bool isConfigured,
|
||||
string? notConfiguredReason,
|
||||
IReadOnlyDictionary<string, string> parameters,
|
||||
IReadOnlyDictionary<string, ValueSource> headers,
|
||||
IReadOnlyDictionary<string, ValueSource> body,
|
||||
JsonElement? variables,
|
||||
IReadOnlyList<string> rootFields,
|
||||
string? sample,
|
||||
IReadOnlySet<string> required,
|
||||
IReadOnlySet<string> optional)
|
||||
{
|
||||
Name = name;
|
||||
Kind = kind;
|
||||
Method = method;
|
||||
Path = path;
|
||||
Category = category;
|
||||
IsConfigured = isConfigured;
|
||||
NotConfiguredReason = notConfiguredReason;
|
||||
Parameters = parameters;
|
||||
Headers = headers;
|
||||
Body = body;
|
||||
Variables = variables;
|
||||
RootFields = rootFields;
|
||||
Sample = sample;
|
||||
RequiredValues = required;
|
||||
OptionalValues = optional;
|
||||
PathShape = Placeholder().Replace(path, m => CaseValues.ShapeOf(m.Groups[1].Value));
|
||||
PathValues = Placeholder().Matches(path).Select(m => m.Groups[1].Value).ToFrozenSet(StringComparer.Ordinal);
|
||||
PendingValues = [.. headers.Where(h => h.Value.Kind == ValueSourceKind.Pending).Select(h => h.Key)
|
||||
.Concat(body.Where(b => b.Value.Kind == ValueSourceKind.Pending).Select(b => b.Key))];
|
||||
}
|
||||
|
||||
/// <summary>The name a <see cref="SiteRequest"/> asks for: for GraphQL the friendly name of the site's query.</summary>
|
||||
public string Name { get; }
|
||||
|
||||
public OperationKind Kind { get; }
|
||||
|
||||
/// <summary><c>GET</c> or <c>POST</c> (POST only for GraphQL queries).</summary>
|
||||
public string Method { get; }
|
||||
|
||||
/// <summary>The path, with the values of the case as <c>{account_id}</c>, <c>{media_id}</c>…</summary>
|
||||
public string Path { get; }
|
||||
|
||||
/// <summary>The path as the log may show it (<c>/api/v1/media/{numero}/info/</c>): never a value.</summary>
|
||||
public string PathShape { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The category of the Governor the request counts in (§7.4: a permit per request, in the category of what it
|
||||
/// asks). Mapped on the existing categories, the budgets per request are recomputed in tappa S3: the profile header
|
||||
/// and the list of a profile's collections count as <see cref="ActionKind.ProfileOpen"/>; a page of posts, reels or
|
||||
/// tagged contents as <see cref="ActionKind.BackfillPage"/> (the first page too); stories and highlights as
|
||||
/// <see cref="ActionKind.StoryView"/>; a single post as <see cref="ActionKind.SinglePost"/>; the search box as
|
||||
/// <see cref="ActionKind.ProfileSearch"/>; the home as <see cref="ActionKind.Home"/>; the followed list as
|
||||
/// <see cref="ActionKind.FollowingListPage"/>. The file names the category, but the code pins the one budget outside
|
||||
/// the sessions: <see cref="ActionKind.ProfileSearch"/> only for an operation that carries <c>{search_text}</c> and no
|
||||
/// account or content, and every operation carrying <c>{search_text}</c> counts there.
|
||||
/// </summary>
|
||||
public ActionKind Category { get; }
|
||||
|
||||
/// <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"/>):
|
||||
/// the site client refuses it (rule 9: what is not known is not guessed). A configured operation has no
|
||||
/// <see cref="PendingValues"/>: the catalog refuses the file otherwise.
|
||||
/// </summary>
|
||||
public bool IsConfigured { get; }
|
||||
|
||||
/// <summary>Why it is not configured, in Italian; null when it is.</summary>
|
||||
public string? NotConfiguredReason { get; }
|
||||
|
||||
/// <summary>Query string of a plain address: name and template (<c>{cursor}</c>, <c>{cursor?}</c> when optional, <c>constant:…</c>).</summary>
|
||||
public IReadOnlyDictionary<string, string> Parameters { get; }
|
||||
|
||||
/// <summary>The names of the headers and where each value comes from. Cookies are not a header here: they come from the saved session.</summary>
|
||||
public IReadOnlyDictionary<string, ValueSource> Headers { get; }
|
||||
|
||||
/// <summary>The form fields of a GraphQL query and where each value comes from.</summary>
|
||||
public IReadOnlyDictionary<string, ValueSource> Body { get; }
|
||||
|
||||
/// <summary>The template of the variables of a GraphQL query: constants as the shapes show them, <c>"{name}"</c> for a value of the case.</summary>
|
||||
public JsonElement? Variables { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Fields every answer must have (dotted paths from the root, e.g. <c>data.user</c>): a JSON without them stops the
|
||||
/// session and warns (§6.0, §7.6). From the request shapes (<c>campo_radice</c>) or the cleaned sample.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> RootFields { get; }
|
||||
|
||||
/// <summary>The cleaned sample of <c>tests/Febe.Tests/campioni/<sito></c> that documents the answer (file name without extension).</summary>
|
||||
public string? Sample { get; }
|
||||
|
||||
/// <summary>Values of the case the request must carry.</summary>
|
||||
public IReadOnlySet<string> RequiredValues { get; }
|
||||
|
||||
/// <summary>Values of the case the request may carry (optional query parameters).</summary>
|
||||
public IReadOnlySet<string> OptionalValues { get; }
|
||||
|
||||
/// <summary>Headers and form fields whose source is not settled yet (<see cref="ValueSourceKind.Pending"/>).</summary>
|
||||
public IReadOnlyList<string> PendingValues { get; }
|
||||
|
||||
/// <summary>Why <paramref name="request"/> does not fit this operation (in Italian, names only), or null.</summary>
|
||||
public string? CheckValues(SiteRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var missing = RequiredValues.Where(v => !request.Values.ContainsKey(v)).Order(StringComparer.Ordinal).ToList();
|
||||
if (missing.Count > 0)
|
||||
{
|
||||
return $"manca il valore {string.Join(", ", missing.Select(m => $"«{m}»"))}.";
|
||||
}
|
||||
|
||||
var extra = request.Values.Keys.Where(v => !RequiredValues.Contains(v) && !OptionalValues.Contains(v)).Order(StringComparer.Ordinal).ToList();
|
||||
if (extra.Count > 0)
|
||||
{
|
||||
return $"il valore {string.Join(", ", extra.Select(e => $"«{e}»"))} non serve a questa operazione.";
|
||||
}
|
||||
|
||||
// A value that fills a segment of the path must stay that segment: nothing the HTTP stack would read as another
|
||||
// segment, a query or a step up («/», «?», «#», «%», «.», «..»).
|
||||
var unsafeInPath = PathValues.Where(v => request.Values.TryGetValue(v, out var value) && !IsPlainSegment(value)).Order(StringComparer.Ordinal).ToList();
|
||||
return unsafeInPath.Count > 0
|
||||
? $"il valore {string.Join(", ", unsafeInPath.Select(v => $"«{v}»"))} non può stare nel percorso (contiene «/», «?», «#», «%», spazi o è fatto solo di punti)."
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>Values of the case that fill a segment of <see cref="Path"/>.</summary>
|
||||
public IReadOnlySet<string> PathValues { get; }
|
||||
|
||||
private static bool IsPlainSegment(string value) =>
|
||||
value.Length > 0
|
||||
&& value.Trim('.').Length > 0
|
||||
&& !value.Any(c => c is '/' or '\\' or '?' or '#' or '%' or ';' || char.IsWhiteSpace(c) || char.IsControl(c));
|
||||
|
||||
/// <summary>True when the answer has every field of <see cref="RootFields"/> (not null).</summary>
|
||||
public bool HasRootFields(JsonElement root)
|
||||
{
|
||||
foreach (var field in RootFields)
|
||||
{
|
||||
var node = root;
|
||||
foreach (var part in field.Split('.'))
|
||||
{
|
||||
if (node.ValueKind != JsonValueKind.Object || !node.TryGetProperty(part, out node))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (node.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The name, the shape of the path and the state: what the log may show.</summary>
|
||||
public override string ToString() => $"{Name} ({Method} {PathShape}{(IsConfigured ? string.Empty : ", non configurata")})";
|
||||
|
||||
[GeneratedRegex(@"\{([a-z_]+)\??\}", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Placeholder();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The operations the site client may ask (issue #36, spec §6.0), loaded from <c>richieste.<sito>.json</c> like the
|
||||
/// other configuration files: a copy embedded in Febe, an editable copy in the Data folder that wins.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The file only narrows: the refusals are in the code, so an edited copy cannot lift them. At load time the catalog
|
||||
/// refuses, with an Italian message naming the file and the operation:
|
||||
/// <list type="bullet">
|
||||
/// <item>any operation whose name contains <c>Mutation</c> (the site's writes; the request shapes show them as
|
||||
/// <c>…Mutation</c>), and the GraphQL families of chat, inbox, presence, promotions and telemetry
|
||||
/// (<see cref="ForbiddenNamePrefixes"/>, <see cref="ForbiddenNameParts"/>);</item>
|
||||
/// <item>the paths of telemetry, navigation and the site's own scripts (<see cref="ForbiddenPathPrefixes"/>), any path
|
||||
/// with a host or a query string, any segment that is empty, <c>.</c> or <c>..</c> (the HTTP stack would rewrite it),
|
||||
/// any character outside letters, digits and <c>/_.-{}</c>, any path whose first segment is a value, GraphQL outside
|
||||
/// its two entry points and a plain address that points at one of them;</item>
|
||||
/// <item>a plain address that is not read with GET, a GraphQL query without its variables, a header <c>cookie</c>,
|
||||
/// <c>host</c> or <c>authorization</c>, an unknown key, source, category or value name, the category «ricerca» for
|
||||
/// anything but a search (<see cref="SiteOperation.Category"/>).</item>
|
||||
/// </list>
|
||||
/// An operation is «configured» only when the shapes tell everything it needs, every header and field included (no
|
||||
/// <see cref="ValueSourceKind.Pending"/>); otherwise the file says why, and the site client refuses it.
|
||||
/// </remarks>
|
||||
public sealed partial class RequestCatalog
|
||||
{
|
||||
/// <summary>Written by the probe in place of a name that elsewhere was a value: the real name is unknown.</summary>
|
||||
public const string RemovedName = "(nome tolto)";
|
||||
|
||||
/// <summary>Written in a template in place of a value the shapes do not show.</summary>
|
||||
public const string RemovedValue = "(valore tolto)";
|
||||
|
||||
/// <summary>The two GraphQL entry points seen in the request shapes.</summary>
|
||||
public static IReadOnlySet<string> GraphQlPaths { get; } = new[] { "/api/graphql", "/graphql/query" }.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Paths never asked, also when an edited file lists them: telemetry, navigation and scripts of the page, chat.</summary>
|
||||
public static IReadOnlyList<string> ForbiddenPathPrefixes { get; } =
|
||||
[
|
||||
"/logging_client_events", "/ajax/bz", "/ajax/bulk-route-definitions/", "/ajax/navigation/", "/ajax/", "/ws/",
|
||||
"/api/v1/web/", "/api/v1/discover/web/", "/api/v1/direct_v2/", "/api/v1/qp/",
|
||||
];
|
||||
|
||||
/// <summary>Beginnings of the GraphQL names of chat, inbox, presence, promotions, telemetry and ads, never asked.</summary>
|
||||
public static IReadOnlyList<string> ForbiddenNamePrefixes { get; } =
|
||||
[
|
||||
"IGD", "IGPresence", "PolarisDirect", "useIGDSystem", "QuickPromotion", "PolarisAPIGetFrCookie", "useFeatureLimits",
|
||||
"PolarisStoriesV3Seen", "PolarisStoriesV3AdsPool", "usePolarisLike", "usePolarisRegisterInRecentSearches",
|
||||
"PolarisProfileDirectOrPartnershipInbox",
|
||||
];
|
||||
|
||||
/// <summary>Parts of a name that make it a write or a chat operation wherever they stand.</summary>
|
||||
public static IReadOnlyList<string> ForbiddenNameParts { get; } = ["Mutation", "Inbox", "Msys", "Presence"];
|
||||
|
||||
private static readonly FrozenSet<string> ForbiddenHeaders = new[]
|
||||
{
|
||||
"cookie", "host", "authorization", "proxy-authorization", "connection", "transfer-encoding", "set-cookie",
|
||||
}.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
private readonly FrozenDictionary<string, SiteOperation> _byName;
|
||||
|
||||
private RequestCatalog(string site, IReadOnlyList<SiteOperation> operations, string? source)
|
||||
{
|
||||
Site = site;
|
||||
Operations = operations;
|
||||
Source = source ?? $"richieste.{site}.json";
|
||||
_byName = operations.ToFrozenDictionary(o => o.Name, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>The site name of the file (<c>instagram</c>, <c>prova</c>).</summary>
|
||||
public string Site { get; }
|
||||
|
||||
/// <summary>Every operation, in the order of the file.</summary>
|
||||
public IReadOnlyList<SiteOperation> Operations { get; }
|
||||
|
||||
/// <summary>Where it came from (file path or embedded name), for messages.</summary>
|
||||
public string Source { get; }
|
||||
|
||||
/// <summary>The configured operations.</summary>
|
||||
public IEnumerable<SiteOperation> Configured => Operations.Where(o => o.IsConfigured);
|
||||
|
||||
public bool TryGet(string name, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out SiteOperation? operation) =>
|
||||
_byName.TryGetValue(name, out operation);
|
||||
|
||||
/// <summary>The Instagram catalog (embedded <c>richieste.instagram.json</c>).</summary>
|
||||
public static RequestCatalog LoadInstagram() => LoadEmbedded("richieste.instagram.json");
|
||||
|
||||
/// <summary>The catalog of the local test site (embedded <c>richieste.prova.json</c>).</summary>
|
||||
public static RequestCatalog LoadTestSite() => LoadEmbedded("richieste.prova.json");
|
||||
|
||||
/// <summary>Loads <paramref name="path"/> when it exists, otherwise the embedded file with the same name.</summary>
|
||||
public static RequestCatalog LoadOrEmbedded(string? path, string embeddedName) =>
|
||||
!string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadEmbedded(embeddedName);
|
||||
|
||||
public static RequestCatalog Load(string path) => Parse(File.ReadAllText(path), path);
|
||||
|
||||
public static RequestCatalog LoadEmbedded(string fileName) => Parse(SiteMap.ReadEmbeddedText(fileName), fileName);
|
||||
|
||||
/// <exception cref="InvalidDataException">The file is not valid or lists something the catalog refuses.</exception>
|
||||
public static RequestCatalog Parse(string json, string? source = null)
|
||||
{
|
||||
var name = source ?? "richieste";
|
||||
CatalogFile? file;
|
||||
try
|
||||
{
|
||||
file = JsonSerializer.Deserialize(json, RequestCatalogJsonContext.Default.CatalogFile);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{name}: file non valido (riga {(ex.LineNumber ?? 0) + 1}): {ex.Message.Split('.')[0]}.", ex);
|
||||
}
|
||||
|
||||
if (file is null || string.IsNullOrWhiteSpace(file.Site))
|
||||
{
|
||||
throw new InvalidDataException($"{name}: manca «site».");
|
||||
}
|
||||
|
||||
if (file.Operations is null)
|
||||
{
|
||||
throw new InvalidDataException($"{name}: manca l'elenco «operations».");
|
||||
}
|
||||
|
||||
var operations = new List<SiteOperation>(file.Operations.Count);
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
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.");
|
||||
var operation = ToOperation(dto, $"{name}, operazione {(i + 1).ToString(CultureInfo.InvariantCulture)}");
|
||||
if (!names.Add(operation.Name))
|
||||
{
|
||||
throw new InvalidDataException($"{name}: l'operazione «{operation.Name}» compare due volte.");
|
||||
}
|
||||
|
||||
operations.Add(operation);
|
||||
}
|
||||
|
||||
return new RequestCatalog(file.Site.Trim(), operations, source);
|
||||
}
|
||||
|
||||
/// <summary>Why the code refuses an operation with this name, whatever the file says; null when it does not.</summary>
|
||||
public static string? RefusalOfName(string operationName)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operationName);
|
||||
foreach (var part in ForbiddenNameParts)
|
||||
{
|
||||
if (operationName.Contains(part, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return part == "Mutation"
|
||||
? "è una scrittura («Mutation»): Febe chiede solo letture (regola 6)"
|
||||
: $"è della famiglia di chat, messaggi o presenza («{part}»), che Febe non chiede mai";
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var prefix in ForbiddenNamePrefixes)
|
||||
{
|
||||
if (operationName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return $"è della famiglia «{prefix}» (chat, messaggi, presenza, promozioni, pubblicità o telemetria), che Febe non chiede mai";
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Why the code refuses this path, whatever the file says; null when it does not.</summary>
|
||||
public static string? RefusalOfPath(string path)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(path);
|
||||
if (!path.StartsWith('/') || path.StartsWith("//", StringComparison.Ordinal) || path.Contains("://", StringComparison.Ordinal)
|
||||
|| path.Contains('\\', StringComparison.Ordinal))
|
||||
{
|
||||
return "un percorso comincia con una sola «/» e non nomina un host: Febe chiede solo al sito";
|
||||
}
|
||||
|
||||
if (path.IndexOfAny(['?', '#']) >= 0)
|
||||
{
|
||||
return "un percorso non porta parametri: vanno in «parameters»";
|
||||
}
|
||||
|
||||
if (path.Contains("..", StringComparison.Ordinal) || !PathCharacters().IsMatch(path))
|
||||
{
|
||||
return "il percorso contiene caratteri non ammessi";
|
||||
}
|
||||
|
||||
// The prefixes are compared on the text: no segment the HTTP stack or the server would rewrite («/./», «//»), so
|
||||
// the path that leaves is the one checked here.
|
||||
var segments = path.Split('/');
|
||||
for (var i = 1; i < segments.Length; i++)
|
||||
{
|
||||
if ((segments[i].Length == 0 && i < segments.Length - 1) || segments[i] == ".")
|
||||
{
|
||||
return "un percorso non ha segmenti vuoti («//») né «.»: il percorso che parte è quello scritto";
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var prefix in ForbiddenPathPrefixes)
|
||||
{
|
||||
if (path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
|
||||
|| path.Equals(prefix.TrimEnd('/'), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return $"«{prefix}» è telemetria, navigazione o chat della pagina, che Febe non chiede mai";
|
||||
}
|
||||
}
|
||||
|
||||
var first = path.Split('/', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
|
||||
if (first is null || first.StartsWith('{'))
|
||||
{
|
||||
return "il primo segmento del percorso dev'essere una parola fissa del sito, non un valore";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static SiteOperation ToOperation(OperationDto dto, string where)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dto.Name))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: manca «name».");
|
||||
}
|
||||
|
||||
var name = dto.Name.Trim();
|
||||
where = $"{where} («{name}»)";
|
||||
if (!OperationName().IsMatch(name))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: il nome contiene caratteri non ammessi.");
|
||||
}
|
||||
|
||||
if (RefusalOfName(name) is { } refusedName)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: rifiutata, {refusedName}.");
|
||||
}
|
||||
|
||||
var kind = dto.Kind?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"graphql" => OperationKind.GraphQl,
|
||||
"rest" => OperationKind.Rest,
|
||||
_ => throw new InvalidDataException($"{where}: tipo «{dto.Kind}» sconosciuto (ammessi: graphql, rest)."),
|
||||
};
|
||||
|
||||
var method = dto.Method?.Trim().ToUpperInvariant();
|
||||
var path = dto.Path?.Trim() ?? throw new InvalidDataException($"{where}: manca «path».");
|
||||
if (RefusalOfPath(path) is { } refusedPath)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: rifiutata, {refusedPath}.");
|
||||
}
|
||||
|
||||
var category = ParseCategory(dto.Category, where);
|
||||
var required = new SortedSet<string>(StringComparer.Ordinal);
|
||||
var optional = new SortedSet<string>(StringComparer.Ordinal);
|
||||
foreach (var segment in path.Split('/', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (segment.Contains('{', StringComparison.Ordinal) || segment.Contains('}', StringComparison.Ordinal))
|
||||
{
|
||||
required.Add(CaseValue(segment, where, allowOptional: false, out _));
|
||||
}
|
||||
}
|
||||
|
||||
var parameters = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var (key, value) in dto.Parameters ?? new Dictionary<string, string?>())
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key) || key == RemovedName || !FieldName().IsMatch(key))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: parametro «{key}» non ammesso.");
|
||||
}
|
||||
|
||||
if (value is null || value.Length == 0)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: il parametro «{key}» non dice il suo valore.");
|
||||
}
|
||||
|
||||
if (value.StartsWith('{'))
|
||||
{
|
||||
var caseValue = CaseValue(value, where, allowOptional: true, out var isOptional);
|
||||
(isOptional ? optional : required).Add(caseValue);
|
||||
}
|
||||
else if (!value.StartsWith("constant:", StringComparison.Ordinal) || value.Length == "constant:".Length)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: il parametro «{key}» vale «{{valore del caso}}» o «constant:…».");
|
||||
}
|
||||
|
||||
parameters[key] = value;
|
||||
}
|
||||
|
||||
var headers = Sources(dto.Headers, where, "intestazione", isBody: false);
|
||||
foreach (var header in headers.Keys)
|
||||
{
|
||||
if (ForbiddenHeaders.Contains(header))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: l'intestazione «{header}» non si scrive nel modello (i cookie vengono dalla sessione salvata, l'host è quello del sito).");
|
||||
}
|
||||
}
|
||||
|
||||
if (headers.TryGetValue("user-agent", out var userAgent) && userAgent != new ValueSource(ValueSourceKind.Session, "user_agent"))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «user-agent» è quello del browser, copiato tale e quale («session:user_agent», regola 4).");
|
||||
}
|
||||
|
||||
var body = Sources(dto.Body, where, "campo", isBody: true);
|
||||
JsonElement? variables = null;
|
||||
var removedInVariables = false;
|
||||
if (kind == OperationKind.GraphQl)
|
||||
{
|
||||
if (method != "POST")
|
||||
{
|
||||
throw new InvalidDataException($"{where}: una richiesta GraphQL si fa con POST.");
|
||||
}
|
||||
|
||||
if (!GraphQlPaths.Contains(path))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: una richiesta GraphQL va a {string.Join(" o ", GraphQlPaths)}.");
|
||||
}
|
||||
|
||||
if (parameters.Count > 0)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: una richiesta GraphQL non ha parametri nell'indirizzo.");
|
||||
}
|
||||
|
||||
RequireSource(body, "variables", new ValueSource(ValueSourceKind.Variables, null), where);
|
||||
RequireSource(body, "doc_id", new ValueSource(ValueSourceKind.Session, "doc_id"), where);
|
||||
RequireSource(body, "fb_api_req_friendly_name", new ValueSource(ValueSourceKind.Operation, null), where);
|
||||
if (headers.TryGetValue("x-fb-friendly-name", out var friendly) && friendly.Kind != ValueSourceKind.Operation)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «x-fb-friendly-name» è il nome dell'operazione («operation»).");
|
||||
}
|
||||
|
||||
if (dto.Variables is not { ValueKind: JsonValueKind.Object } template)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: manca «variables» (un oggetto, come nelle forme delle richieste).");
|
||||
}
|
||||
|
||||
removedInVariables = Template(template, where, required, depth: 0);
|
||||
variables = template.Clone();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (method != "GET")
|
||||
{
|
||||
throw new InvalidDataException($"{where}: un indirizzo semplice si legge solo con GET (sola lettura).");
|
||||
}
|
||||
|
||||
// A GET to a GraphQL entry point would skip the checks of a GraphQL query (doc_id from the session, the
|
||||
// friendly name that is the operation's and that the refusal of «Mutation» looks at).
|
||||
if (path.Split('/').Any(s => s.Contains("graphql", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: rifiutata, una richiesta GraphQL si scrive con «kind»: «graphql», non come indirizzo semplice.");
|
||||
}
|
||||
|
||||
if (body.Count > 0 || dto.Variables is { ValueKind: not JsonValueKind.Null and not JsonValueKind.Undefined })
|
||||
{
|
||||
throw new InvalidDataException($"{where}: una lettura con GET non ha «body» né «variables».");
|
||||
}
|
||||
}
|
||||
|
||||
// The search budget belongs to no session and spares the collection caps (§7.4): only a search may count there,
|
||||
// and a search counts nowhere else, whatever an edited copy says.
|
||||
var searches = required.Contains(CaseValues.SearchText) || optional.Contains(CaseValues.SearchText);
|
||||
if (category == ActionKind.ProfileSearch
|
||||
&& (!required.Contains(CaseValues.SearchText) || required.Concat(optional).Any(v => v is not (CaseValues.SearchText or CaseValues.Cursor))))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: rifiutata, la categoria «ricerca» è solo di una ricerca, che porta «{{{CaseValues.SearchText}}}» e nessun account o contenuto.");
|
||||
}
|
||||
|
||||
if (searches && category != ActionKind.ProfileSearch)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: rifiutata, un'operazione che porta «{{{CaseValues.SearchText}}}» è una ricerca (categoria «ricerca»).");
|
||||
}
|
||||
|
||||
var rootFields = (dto.RootFields ?? []).Select(f => f?.Trim() ?? string.Empty).ToList();
|
||||
if (rootFields.Any(f => !RootField().IsMatch(f)))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «rootFields» elenca campi come «data.user», separati da punti.");
|
||||
}
|
||||
|
||||
var sample = string.IsNullOrWhiteSpace(dto.Sample) ? null : dto.Sample.Trim();
|
||||
if (sample is not null && !SampleName().IsMatch(sample))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «sample» è il nome di un campione ripulito, come «000005-post-video».");
|
||||
}
|
||||
|
||||
var configured = dto.Configured ?? throw new InvalidDataException($"{where}: manca «configured» (true o false).");
|
||||
var reason = string.IsNullOrWhiteSpace(dto.Reason) ? null : dto.Reason.Trim();
|
||||
if (configured)
|
||||
{
|
||||
if (reason is not null)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «reason» si scrive solo per un'operazione non configurata.");
|
||||
}
|
||||
|
||||
if (removedInVariables)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: le variabili hanno un nome o un valore tolto dalla sonda: non può essere configurata (regola 9).");
|
||||
}
|
||||
|
||||
// Every header and field the model lists leaves with its value, or the request is not the browser's (rule 4):
|
||||
// one whose source is not settled, or whose name the probe removed, keeps the operation not configured.
|
||||
var pending = headers.Where(h => h.Value.Kind == ValueSourceKind.Pending).Select(h => h.Key)
|
||||
.Concat(body.Where(b => b.Value.Kind == ValueSourceKind.Pending).Select(b => b.Key)).ToList();
|
||||
if (pending.Count > 0)
|
||||
{
|
||||
throw new InvalidDataException(
|
||||
$"{where}: {pending.Count.ToString(CultureInfo.InvariantCulture)} intestazioni o campi hanno la fonte «pending» (come {string.Join(", ", pending.Take(3).Select(p => $"«{p}»"))}): non può essere configurata finché non si sa da dove vengono i valori (regola 9).");
|
||||
}
|
||||
|
||||
if (sample is null || rootFields.Count == 0)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: un'operazione configurata dice il campione della risposta («sample») e i campi attesi («rootFields»).");
|
||||
}
|
||||
}
|
||||
else if (reason is null)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: un'operazione non configurata dice perché («reason»).");
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
private static Dictionary<string, ValueSource> Sources(Dictionary<string, string?>? entries, string where, string what, bool isBody)
|
||||
{
|
||||
var result = new Dictionary<string, ValueSource>(StringComparer.Ordinal);
|
||||
foreach (var (key, text) in entries ?? new Dictionary<string, string?>())
|
||||
{
|
||||
var isRemoved = key == RemovedName;
|
||||
if (!isRemoved && (isBody ? !FieldName().IsMatch(key) : !HeaderName().IsMatch(key)))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: {what} «{key}» non ammesso{(isBody ? string.Empty : " (nomi in minuscolo)")}.");
|
||||
}
|
||||
|
||||
var source = ParseSource(text, $"{where}, {what} «{key}»");
|
||||
if (isRemoved && source.Kind != ValueSourceKind.Pending)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: un {what} con il nome tolto dalla sonda vale solo «pending».");
|
||||
}
|
||||
|
||||
if (source.Kind == ValueSourceKind.Variables && !(isBody && key == "variables"))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «variables» è la fonte del solo campo «variables».");
|
||||
}
|
||||
|
||||
result[key] = source;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static ValueSource ParseSource(string? text, string where)
|
||||
{
|
||||
var value = text ?? string.Empty;
|
||||
var colon = value.IndexOf(':', StringComparison.Ordinal);
|
||||
var head = colon < 0 ? value : value[..colon];
|
||||
var argument = colon < 0 ? null : value[(colon + 1)..];
|
||||
switch (head)
|
||||
{
|
||||
case "constant" when !string.IsNullOrEmpty(argument):
|
||||
return new ValueSource(ValueSourceKind.Constant, argument);
|
||||
case "cookie" when argument is not null && CookieName().IsMatch(argument):
|
||||
return new ValueSource(ValueSourceKind.Cookie, argument);
|
||||
case "session" when argument is not null && ValueSource.SessionFields.Contains(argument):
|
||||
return new ValueSource(ValueSourceKind.Session, argument);
|
||||
case "operation" when argument is null:
|
||||
return new ValueSource(ValueSourceKind.Operation, null);
|
||||
case "variables" when argument is null:
|
||||
return new ValueSource(ValueSourceKind.Variables, null);
|
||||
case "computed" when argument is null:
|
||||
return new ValueSource(ValueSourceKind.Computed, null);
|
||||
case "pending" when argument is null:
|
||||
return new ValueSource(ValueSourceKind.Pending, null);
|
||||
default:
|
||||
throw new InvalidDataException(
|
||||
$"{where}: fonte «{value}» sconosciuta (ammesse: constant:…, cookie:…, session:{string.Join("|", ValueSource.SessionFields.Order(StringComparer.Ordinal))}, operation, variables, computed, pending).");
|
||||
}
|
||||
}
|
||||
|
||||
private static void RequireSource(Dictionary<string, ValueSource> body, string field, ValueSource expected, string where)
|
||||
{
|
||||
if (!body.TryGetValue(field, out var actual) || actual != expected)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: una richiesta GraphQL ha il campo «{field}» con la fonte «{expected}».");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Checks a variables template; collects its values of the case; true when it holds removed names or values.</summary>
|
||||
private static bool Template(JsonElement element, string where, SortedSet<string> required, int depth)
|
||||
{
|
||||
if (depth > 16)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «variables» è troppo profondo.");
|
||||
}
|
||||
|
||||
var removed = false;
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
removed |= property.Name == RemovedName;
|
||||
removed |= Template(property.Value, where, required, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
removed |= Template(item, where, required, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.String:
|
||||
var text = element.GetString()!;
|
||||
if (text == RemovedValue)
|
||||
{
|
||||
removed = true;
|
||||
}
|
||||
else if (text.StartsWith('{') || text.EndsWith('}'))
|
||||
{
|
||||
required.Add(CaseValue(text, where, allowOptional: false, out _));
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
private static string CaseValue(string text, string where, bool allowOptional, out bool isOptional)
|
||||
{
|
||||
var match = CaseValuePattern().Match(text);
|
||||
isOptional = match.Success && match.Groups[2].Success;
|
||||
if (!match.Success || (isOptional && !allowOptional) || !CaseValues.All.Contains(match.Groups[1].Value))
|
||||
{
|
||||
throw new InvalidDataException(
|
||||
$"{where}: «{text}» non è un valore del caso (ammessi: {string.Join(", ", CaseValues.All.Order(StringComparer.Ordinal).Select(v => $"{{{v}}}"))}{(allowOptional ? ", con «?» se facoltativo" : string.Empty)}).");
|
||||
}
|
||||
|
||||
return match.Groups[1].Value;
|
||||
}
|
||||
|
||||
private static ActionKind ParseCategory(string? value, string where) => value?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"home" => ActionKind.Home,
|
||||
"profilo" => ActionKind.ProfileOpen,
|
||||
"storia" => ActionKind.StoryView,
|
||||
"storico" => ActionKind.BackfillPage,
|
||||
"post" => ActionKind.SinglePost,
|
||||
"seguiti" => ActionKind.FollowingListPage,
|
||||
"ricerca" => ActionKind.ProfileSearch,
|
||||
_ => throw new InvalidDataException($"{where}: categoria «{value}» sconosciuta (ammesse: home, profilo, storia, storico, post, seguiti, ricerca)."),
|
||||
};
|
||||
|
||||
[GeneratedRegex(@"^[A-Za-z][A-Za-z0-9_.-]{0,127}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex OperationName();
|
||||
|
||||
[GeneratedRegex(@"^[A-Za-z0-9/_.{}-]+$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex PathCharacters();
|
||||
|
||||
[GeneratedRegex(@"^[A-Za-z_][A-Za-z0-9_]{0,63}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex FieldName();
|
||||
|
||||
[GeneratedRegex(@"^[a-z][a-z0-9-]{0,63}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex HeaderName();
|
||||
|
||||
[GeneratedRegex(@"^[A-Za-z0-9_.-]{1,64}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex CookieName();
|
||||
|
||||
[GeneratedRegex(@"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex RootField();
|
||||
|
||||
[GeneratedRegex(@"^[0-9]{6}-[a-z0-9-]+$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex SampleName();
|
||||
|
||||
[GeneratedRegex(@"^\{([a-z_]+)(\?)?\}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex CaseValuePattern();
|
||||
}
|
||||
|
||||
internal sealed class CatalogFile
|
||||
{
|
||||
public string? Site { get; set; }
|
||||
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<OperationDto?>? Operations { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class OperationDto
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
|
||||
public string? Kind { get; set; }
|
||||
|
||||
public string? Method { get; set; }
|
||||
|
||||
public string? Path { get; set; }
|
||||
|
||||
public string? Category { get; set; }
|
||||
|
||||
public bool? Configured { get; set; }
|
||||
|
||||
public string? Reason { get; set; }
|
||||
|
||||
public Dictionary<string, string?>? Parameters { get; set; }
|
||||
|
||||
public Dictionary<string, string?>? Headers { get; set; }
|
||||
|
||||
public Dictionary<string, string?>? Body { get; set; }
|
||||
|
||||
public JsonElement? Variables { get; set; }
|
||||
|
||||
public List<string?>? RootFields { get; set; }
|
||||
|
||||
public string? Sample { get; set; }
|
||||
|
||||
public List<string>? Shapes { get; set; }
|
||||
|
||||
public string? Note { get; set; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
AllowTrailingCommas = true,
|
||||
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow)]
|
||||
[JsonSerializable(typeof(CatalogFile))]
|
||||
internal sealed partial class RequestCatalogJsonContext : JsonSerializerContext;
|
||||
@@ -0,0 +1,195 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Febe.Core.Collection.Privacy;
|
||||
|
||||
namespace Febe.Core.Collection.Requests;
|
||||
|
||||
/// <summary>
|
||||
/// What the site answered to one <see cref="SiteRequest"/> (issue #36, spec §6.0), with what the stop signals of §7.6
|
||||
/// need: the status, the declared type, whether it was a redirect and where to (the shape of the path only, never
|
||||
/// followed), and the names of the cookies the site set or deleted. The body lives in memory only, for the time of the
|
||||
/// reading (§6.2).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It never holds a value of a header or of a cookie: the site client keeps the renewed cookies and the
|
||||
/// <c>x-ig-www-claim</c> in the saved session itself (decision of 16 November 2026) and reports here only that they
|
||||
/// came. Its text (<see cref="ToString"/>) shows the operation, the shape of the path, the status, the type and the
|
||||
/// sizes, never the body, the cookies, a query string or the variables (rule 10).
|
||||
/// </remarks>
|
||||
public sealed class SiteAnswer
|
||||
{
|
||||
/// <param name="operation">
|
||||
/// The catalog operation that was asked: its name and its <see cref="SiteOperation.PathShape"/> are what the answer
|
||||
/// shows, so the path with its values (an identifier, a user name) can never be passed in its place.
|
||||
/// </param>
|
||||
/// <param name="status">HTTP status.</param>
|
||||
/// <param name="mimeType">Declared type (parameters such as the charset are dropped).</param>
|
||||
/// <param name="body">The body, decoded (memory only).</param>
|
||||
/// <param name="redirectTo">For a redirect, the <c>Location</c> as the site sent it: only the shape of its path is kept.</param>
|
||||
/// <param name="cookiesSet">Names of the cookies the site set (<c>Set-Cookie</c> with a value).</param>
|
||||
/// <param name="cookiesDeleted">Names of the cookies the site deleted (<c>Set-Cookie</c> expired or empty).</param>
|
||||
/// <param name="setsClaim">True when the site sent a new <c>x-ig-www-claim</c> (<c>x-ig-set-www-claim</c>).</param>
|
||||
/// <param name="retryAfter">What a <c>Retry-After</c> asked to wait, when the site sent one.</param>
|
||||
/// <exception cref="ArgumentException">A cookie name that is not a plain name (a value must never slip in).</exception>
|
||||
public SiteAnswer(
|
||||
SiteOperation operation,
|
||||
int status,
|
||||
string? mimeType,
|
||||
ReadOnlyMemory<byte> body,
|
||||
string? redirectTo = null,
|
||||
IEnumerable<string>? cookiesSet = null,
|
||||
IEnumerable<string>? cookiesDeleted = null,
|
||||
bool setsClaim = false,
|
||||
TimeSpan? retryAfter = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operation);
|
||||
Operation = operation.Name;
|
||||
PathShape = operation.PathShape;
|
||||
Status = status;
|
||||
MimeType = (mimeType ?? string.Empty).Split(';')[0].Trim().ToLowerInvariant();
|
||||
Body = body;
|
||||
IsRedirect = status is >= 300 and < 400;
|
||||
RedirectPathShape = IsRedirect || redirectTo is not null ? ShapeOfLocation(redirectTo) : null;
|
||||
CookiesSet = Names(cookiesSet, nameof(cookiesSet));
|
||||
CookiesDeleted = Names(cookiesDeleted, nameof(cookiesDeleted));
|
||||
SetsClaim = setsClaim;
|
||||
RetryAfter = retryAfter;
|
||||
}
|
||||
|
||||
/// <summary>Name of the catalog operation that was asked.</summary>
|
||||
public string Operation { get; }
|
||||
|
||||
/// <summary>Shape of the path asked (<c>/api/v1/media/{numero}/info/</c>): what the log may show.</summary>
|
||||
public string PathShape { get; }
|
||||
|
||||
public int Status { get; }
|
||||
|
||||
/// <summary>Declared type, lower case, without parameters.</summary>
|
||||
public string MimeType { get; }
|
||||
|
||||
/// <summary>The body (memory only, never logged).</summary>
|
||||
public ReadOnlyMemory<byte> Body { get; }
|
||||
|
||||
/// <summary>True for a 3xx: a signal (§7.6), never an address to visit.</summary>
|
||||
public bool IsRedirect { get; }
|
||||
|
||||
/// <summary>
|
||||
/// For a redirect, the shape of the path it pointed to (<c>/accounts/login/</c>, <c>/challenge/{testo}/</c>):
|
||||
/// words of the site kept, everything else <c>{numero}</c> or <c>{testo}</c>, no host, no query string. Empty when
|
||||
/// the site sent no <c>Location</c>.
|
||||
/// </summary>
|
||||
public string? RedirectPathShape { get; }
|
||||
|
||||
/// <summary>Names of the cookies the site set.</summary>
|
||||
public IReadOnlyList<string> CookiesSet { get; }
|
||||
|
||||
/// <summary>Names of the cookies the site deleted (§7.6: the session cookie deleted is a Disconnessione).</summary>
|
||||
public IReadOnlyList<string> CookiesDeleted { get; }
|
||||
|
||||
/// <summary>True when the site sent a new <c>x-ig-www-claim</c> (kept by the site client in the saved session, never here).</summary>
|
||||
public bool SetsClaim { get; }
|
||||
|
||||
/// <summary>What a <c>Retry-After</c> asked to wait (§7.6, Rallentamento).</summary>
|
||||
public TimeSpan? RetryAfter { get; }
|
||||
|
||||
/// <summary>True when the declared type is JSON, or JavaScript as Instagram serves its GraphQL data (<see cref="DataResponses.IsData"/>).</summary>
|
||||
public bool IsDeclaredData => DataResponses.IsData(MimeType, "Fetch");
|
||||
|
||||
/// <summary>True for an HTML document (§7.6: an HTML where the catalog expects JSON stops the session).</summary>
|
||||
public bool IsHtml => MimeType is "text/html" or "application/xhtml+xml";
|
||||
|
||||
/// <summary>True when the site deleted the cookie <paramref name="name"/>.</summary>
|
||||
public bool Deletes(string name) => CookiesDeleted.Contains(name, StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// The shape of the path of a <c>Location</c> (absolute or relative): no scheme, no host, no query string, values
|
||||
/// replaced by <see cref="PathPatterns"/>. Empty for a missing one.
|
||||
/// </summary>
|
||||
public static string ShapeOfLocation(string? location)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(location))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var text = location.Trim();
|
||||
var cut = text.IndexOfAny(['?', '#']);
|
||||
if (cut >= 0)
|
||||
{
|
||||
text = text[..cut];
|
||||
}
|
||||
|
||||
var scheme = text.IndexOf("://", StringComparison.Ordinal);
|
||||
if (scheme >= 0)
|
||||
{
|
||||
var slash = text.IndexOf('/', scheme + 3);
|
||||
text = slash >= 0 ? text[slash..] : "/";
|
||||
}
|
||||
else if (text.StartsWith("//", StringComparison.Ordinal))
|
||||
{
|
||||
var slash = text.IndexOf('/', 2);
|
||||
text = slash >= 0 ? text[slash..] : "/";
|
||||
}
|
||||
|
||||
if (!text.StartsWith('/'))
|
||||
{
|
||||
text = "/" + text;
|
||||
}
|
||||
|
||||
return PathPatterns.Of(text);
|
||||
}
|
||||
|
||||
/// <summary>Operation, path shape, status, type and sizes: never the body, the cookies or a value.</summary>
|
||||
public override string ToString()
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
text.Append(CultureInfo.InvariantCulture, $"Risposta a «{Operation}» ({PathShape}): stato {Status}");
|
||||
text.Append(MimeType.Length == 0 ? ", senza tipo" : $", {MimeType}");
|
||||
text.Append(CultureInfo.InvariantCulture, $", {Body.Length} byte");
|
||||
if (IsRedirect)
|
||||
{
|
||||
text.Append(RedirectPathShape is { Length: > 0 } shape ? $", rinvio a {shape} (non seguito)" : ", rinvio senza indirizzo (non seguito)");
|
||||
}
|
||||
|
||||
if (CookiesSet.Count > 0 || CookiesDeleted.Count > 0)
|
||||
{
|
||||
text.Append(CultureInfo.InvariantCulture, $", cookie impostati {CookiesSet.Count}, cancellati {CookiesDeleted.Count}");
|
||||
}
|
||||
|
||||
if (SetsClaim)
|
||||
{
|
||||
text.Append(", nuovo claim");
|
||||
}
|
||||
|
||||
if (RetryAfter is { } wait)
|
||||
{
|
||||
text.Append(CultureInfo.InvariantCulture, $", attendere {(long)wait.TotalSeconds} s");
|
||||
}
|
||||
|
||||
return text.Append('.').ToString();
|
||||
}
|
||||
|
||||
private static string[] Names(IEnumerable<string>? names, string parameter)
|
||||
{
|
||||
if (names is null)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var list = new List<string>();
|
||||
foreach (var name in names)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name) || name.Any(c => c is '=' or ';' or ',' or '"' || char.IsWhiteSpace(c) || char.IsControl(c)))
|
||||
{
|
||||
throw new ArgumentException("Un nome di cookie non è un nome semplice: qui vanno solo i nomi, mai i valori.", parameter);
|
||||
}
|
||||
|
||||
if (!list.Contains(name, StringComparer.Ordinal))
|
||||
{
|
||||
list.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
return [.. list];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using System.Collections.Frozen;
|
||||
using Febe.Core.Collection.Privacy;
|
||||
|
||||
namespace Febe.Core.Collection.Requests;
|
||||
|
||||
/// <summary>
|
||||
/// Names of the values of the case that a <see cref="SiteRequest"/> may carry (spec §6.0: «variabili con i soli valori
|
||||
/// del caso»): who or what is asked for, and where a list goes on. A closed list: everything else a request carries
|
||||
/// comes from the catalog (<see cref="RequestCatalog"/>) or from the saved session, never from the caller.
|
||||
/// </summary>
|
||||
public static class CaseValues
|
||||
{
|
||||
/// <summary>Numeric identifier of an account on the site.</summary>
|
||||
public const string AccountId = "account_id";
|
||||
|
||||
/// <summary>User name of an account.</summary>
|
||||
public const string Username = "username";
|
||||
|
||||
/// <summary>Cursor of the next page, as the previous answer gave it.</summary>
|
||||
public const string Cursor = "cursor";
|
||||
|
||||
/// <summary>Text typed in the search box.</summary>
|
||||
public const string SearchText = "search_text";
|
||||
|
||||
/// <summary>Numeric identifier of a content (post, reel, story).</summary>
|
||||
public const string MediaId = "media_id";
|
||||
|
||||
/// <summary>Short code of a post, as in its address.</summary>
|
||||
public const string Code = "code";
|
||||
|
||||
/// <summary>Identifier of a highlight (collection of stories).</summary>
|
||||
public const string HighlightId = "highlight_id";
|
||||
|
||||
/// <summary>Every name of the list.</summary>
|
||||
public static IReadOnlySet<string> All { get; } = new[] { AccountId, Username, Cursor, SearchText, MediaId, Code, HighlightId }
|
||||
.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The shape a value takes in a logged path (<see cref="PathPatterns"/>): never the value itself.</summary>
|
||||
public static string ShapeOf(string name) => name is AccountId or MediaId ? PathPatterns.Number : PathPatterns.Text;
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="value"/> has the form of the value <paramref name="name"/>: digits for identifiers,
|
||||
/// the characters of a user name, a short code or a highlight; for a cursor or a searched text, no control
|
||||
/// character. So a value can never carry a path, a query or a step up into the request it fills.
|
||||
/// </summary>
|
||||
public static bool HasForm(string name, string value)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(name);
|
||||
ArgumentNullException.ThrowIfNull(value);
|
||||
return name switch
|
||||
{
|
||||
AccountId or MediaId => value.Length <= 32 && value.Length > 0 && value.All(char.IsAsciiDigit),
|
||||
Username => value.Length <= 64 && value.Trim('.').Length > 0 && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_'),
|
||||
Code => value.Length is > 0 and <= 64 && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-'),
|
||||
HighlightId => value.Length is > 0 and <= 64 && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-' or ':'),
|
||||
Cursor or SearchText => value.Length is > 0 and <= 4096 && !value.Any(char.IsControl),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One request to the site (issue #36, spec §6.0): which operation of the catalog, and the values of the case by name.
|
||||
/// Nothing else: method, path, headers, body and constants come from <c>richieste.<sito>.json</c>, the session
|
||||
/// values from the saved session. Callers never pass raw headers, bodies or addresses.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Its text (<see cref="ToString"/>) names the operation and the names of the values, never the values: user names,
|
||||
/// identifiers, cursors and searched texts stay out of logs (rule 10).
|
||||
/// </remarks>
|
||||
public sealed class SiteRequest
|
||||
{
|
||||
/// <param name="operation">Name of the catalog operation (<see cref="SiteOperation.Name"/>).</param>
|
||||
/// <param name="values">Values of the case, by a name of <see cref="CaseValues"/>.</param>
|
||||
/// <exception cref="ArgumentException">An unknown value name, an empty value, or one without its form (<see cref="CaseValues.HasForm"/>).</exception>
|
||||
public SiteRequest(string operation, IReadOnlyDictionary<string, string>? values = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(operation);
|
||||
var copy = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var (name, value) in values ?? new Dictionary<string, string>())
|
||||
{
|
||||
if (!CaseValues.All.Contains(name))
|
||||
{
|
||||
throw new ArgumentException($"Valore «{name}» sconosciuto: una richiesta porta solo {string.Join(", ", CaseValues.All.Order(StringComparer.Ordinal))}.", nameof(values));
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
throw new ArgumentException($"Il valore «{name}» è vuoto.", nameof(values));
|
||||
}
|
||||
|
||||
if (!CaseValues.HasForm(name, value))
|
||||
{
|
||||
// Never the value in the message: it may be a user name or a searched text (rule 10).
|
||||
throw new ArgumentException($"Il valore «{name}» non ha la forma attesa (cifre per gli identificativi; mai un percorso o una query).", nameof(values));
|
||||
}
|
||||
|
||||
copy[name] = value;
|
||||
}
|
||||
|
||||
Operation = operation.Trim();
|
||||
Values = copy.ToFrozenDictionary(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Name of the catalog operation.</summary>
|
||||
public string Operation { get; }
|
||||
|
||||
/// <summary>Values of the case, by name (never logged).</summary>
|
||||
public IReadOnlyDictionary<string, string> Values { get; }
|
||||
|
||||
/// <summary>A request for <paramref name="operation"/> with the given values.</summary>
|
||||
public static SiteRequest For(string operation, params (string Name, string Value)[] values) =>
|
||||
new(operation, values.ToDictionary(v => v.Name, v => v.Value, StringComparer.Ordinal));
|
||||
|
||||
/// <summary>The operation and the names of the values, never the values.</summary>
|
||||
public override string ToString() =>
|
||||
Values.Count == 0
|
||||
? $"Richiesta «{Operation}»"
|
||||
: $"Richiesta «{Operation}» (valori: {string.Join(", ", Values.Keys.Order(StringComparer.Ordinal))})";
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// Hands the body of one site answer to the <see cref="IResponseConsumer"/>s (spec §6.2, §6.4), whatever brought it:
|
||||
/// the response tap of the browser, or the site client of issue #36 (§6.0). Captured and requested answers reach the
|
||||
/// readers and the stop signals the same way.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A data body is parsed as one JSON answer; a page document is split into the JSON blocks it embeds
|
||||
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>), each an answer of its own. One answer at a time: each
|
||||
/// <see cref="JsonDocument"/> is disposed before the next is parsed. A consumer that fails stops neither the others nor
|
||||
/// the next answer. Bodies stay in memory and are never logged: the warnings name only the consumer's type.
|
||||
/// Thread-safe (the counters are atomic); the caller decides the order of the answers.
|
||||
/// </remarks>
|
||||
public sealed class ResponseDelivery
|
||||
{
|
||||
/// <summary>The depth a body may reach: Instagram's answers go deeper than the default 64.</summary>
|
||||
public const int MaxDepth = 256;
|
||||
|
||||
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = MaxDepth };
|
||||
|
||||
private readonly string _logPrefix;
|
||||
private readonly Action<string, Exception?> _warn;
|
||||
private long _jsonBodies;
|
||||
private long _parseErrors;
|
||||
|
||||
/// <param name="logPrefix">First word of the warnings, in Italian («Cattura», «Client del sito»).</param>
|
||||
/// <param name="warn">Receives the warnings (message and exception); null discards them.</param>
|
||||
public ResponseDelivery(string logPrefix, Action<string, Exception?>? warn = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(logPrefix);
|
||||
_logPrefix = logPrefix;
|
||||
_warn = warn ?? ((_, _) => { });
|
||||
}
|
||||
|
||||
/// <summary>JSON answers handed to the consumers (a page document counts once per block).</summary>
|
||||
public long JsonBodies => Interlocked.Read(ref _jsonBodies);
|
||||
|
||||
/// <summary>Data bodies that were not JSON after all (e.g. Instagram's «for (;;);» answers, or deeper than <see cref="MaxDepth"/>).</summary>
|
||||
public long ParseErrors => Interlocked.Read(ref _parseErrors);
|
||||
|
||||
/// <summary>
|
||||
/// The body of a data answer, as one answer. Returns how many answers reached the consumers: 0 when it is not
|
||||
/// JSON (the caller tells it as <see cref="BodyDropReason.NotJson"/>), otherwise 1.
|
||||
/// </summary>
|
||||
public async Task<int> DeliverBodyAsync(ResponseDescriptor descriptor, ReadOnlyMemory<byte> body, IReadOnlyList<IResponseConsumer> consumers, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(descriptor);
|
||||
ArgumentNullException.ThrowIfNull(consumers);
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
document = JsonDocument.Parse(body, BodyOptions);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Not JSON after all (e.g. Instagram's «for (;;);» answers of /ajax/, which carry no contents): skipped.
|
||||
Interlocked.Increment(ref _parseErrors);
|
||||
return 0;
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
await DeliverAsync(descriptor, document, consumers, ct).ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The JSON blocks a page document embeds, each handed to the consumers as an answer of its own with the document's
|
||||
/// descriptor, so that a pagination stays with the block that carries it. Returns how many blocks reached the
|
||||
/// consumers; a document without any (the caller tells it as <see cref="BodyDropReason.NoJsonBlock"/>) is not data,
|
||||
/// and not a parse error.
|
||||
/// </summary>
|
||||
public async Task<int> DeliverDocumentAsync(ResponseDescriptor descriptor, ReadOnlyMemory<byte> document, IReadOnlyList<IResponseConsumer> consumers, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(descriptor);
|
||||
ArgumentNullException.ThrowIfNull(consumers);
|
||||
var delivered = 0;
|
||||
foreach (var block in DataResponses.EmbeddedJsonBlocks(Encoding.UTF8.GetString(document.Span)))
|
||||
{
|
||||
using (block)
|
||||
{
|
||||
delivered++;
|
||||
await DeliverAsync(descriptor, block, consumers, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return delivered;
|
||||
}
|
||||
|
||||
private async Task DeliverAsync(ResponseDescriptor descriptor, JsonDocument body, IReadOnlyList<IResponseConsumer> consumers, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _jsonBodies);
|
||||
foreach (var consumer in consumers)
|
||||
{
|
||||
try
|
||||
{
|
||||
await consumer.ConsumeAsync(descriptor, body, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
|
||||
{
|
||||
_warn($"{_logPrefix}: errore in un lettore ({consumer.GetType().Name}).", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user