using System.Globalization; using System.Text; using Febe.Core.Collection.Privacy; namespace Febe.Core.Collection.Requests; /// /// What the site answered to one (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). /// /// /// It never holds a value of a header or of a cookie: the site client keeps the renewed cookies and the /// x-ig-www-claim in the saved session itself (decision of 16 November 2026) and reports here only that they /// came. Its text () 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). /// public sealed class SiteAnswer { /// /// The catalog operation that was asked: its name and its are what the answer /// shows, so the path with its values (an identifier, a user name) can never be passed in its place. /// /// HTTP status. /// Declared type (parameters such as the charset are dropped). /// The body, decoded (memory only). /// For a redirect, the Location as the site sent it: only the shape of its path is kept. /// Names of the cookies the site set (Set-Cookie with a value). /// Names of the cookies the site deleted (Set-Cookie expired or empty). /// True when the site sent a new x-ig-www-claim (x-ig-set-www-claim). /// What a Retry-After asked to wait, when the site sent one. /// /// Whether the body is JSON with every field of : true or false when the site /// client looked (it does for every answer), null when nobody did ( then looks itself). /// /// A cookie name that is not a plain name (a value must never slip in). public SiteAnswer( SiteOperation operation, int status, string? mimeType, ReadOnlyMemory body, string? redirectTo = null, IEnumerable? cookiesSet = null, IEnumerable? cookiesDeleted = null, bool setsClaim = false, TimeSpan? retryAfter = null, bool? rootFieldsPresent = 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; RootFieldsPresent = rootFieldsPresent; } /// Name of the catalog operation that was asked. public string Operation { get; } /// Shape of the path asked (/api/v1/media/{numero}/info/): what the log may show. public string PathShape { get; } public int Status { get; } /// Declared type, lower case, without parameters. public string MimeType { get; } /// The body (memory only, never logged). public ReadOnlyMemory Body { get; } /// True for a 3xx: a signal (§7.6), never an address to visit. public bool IsRedirect { get; } /// /// For a redirect, the shape of the path it pointed to (/accounts/login/, /challenge/{testo}/): /// words of the site kept, everything else {numero} or {testo}, no host, no query string. Empty when /// the site sent no Location. /// public string? RedirectPathShape { get; } /// Names of the cookies the site set. public IReadOnlyList CookiesSet { get; } /// Names of the cookies the site deleted (§7.6: the session cookie deleted is a Disconnessione). public IReadOnlyList CookiesDeleted { get; } /// True when the site sent a new x-ig-www-claim (kept by the site client in the saved session, never here). public bool SetsClaim { get; } /// What a Retry-After asked to wait (§7.6, Rallentamento). public TimeSpan? RetryAfter { get; } /// /// True when the body is JSON with every expected field of the operation, false when it is not JSON or misses one /// (§6.0: stop and warn), null when it was not looked at. /// public bool? RootFieldsPresent { get; } /// True when the declared type is JSON, or JavaScript as Instagram serves its GraphQL data (). public bool IsDeclaredData => DataResponses.IsData(MimeType, "Fetch"); /// True for an HTML document (§7.6: an HTML where the catalog expects JSON stops the session). public bool IsHtml => MimeType is "text/html" or "application/xhtml+xml"; /// True when the site deleted the cookie . public bool Deletes(string name) => CookiesDeleted.Contains(name, StringComparer.Ordinal); /// /// The shape of the path of a Location (absolute or relative): no scheme, no host, no query string, values /// replaced by . Empty for a missing one. /// 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); } /// Operation, path shape, status, type and sizes: never the body, the cookies or a value. 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? names, string parameter) { if (names is null) { return []; } var list = new List(); 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]; } }