From 636e7e12510fae4eb02570816ef52710706ed015 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Sat, 26 Sep 2026 16:56:42 +0200 Subject: [PATCH] M2: protocollo di Bidoo, catalogo e trasporto con corsia per le puntate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Parser di data.php e bid.php portati dal legacy con le risposte vere come fixture, lettura del conto (buy_bids, saldo leggero, aste da confermare), pagina dell'asta e indirizzi, catalogo con la paginazione a scorrimento. Indirizzi ed espressioni del sito stanno in bidoo.json (valori di fabbrica nel binario, file in /config riletto a caldo). Trasporto con pool caldo, HTTP/2, token bucket che lascia una riserva al polling e freno su 429/503; corsia dedicata a bid.php con tre connessioni calde. Il runtime dell'immagine passa a Debian 13 con .NET copiato: per .NET 10 non ci sono immagini Debian e su Ubuntu chromium è solo un rimando a snap. Co-Authored-By: Claude Opus 5.5 --- .../src/BidooBidBot/Bidoo/AccountParser.cs | 81 +++ .../BidooBidBot/Bidoo/AuctionPageParser.cs | 103 ++++ Mimante/src/BidooBidBot/Bidoo/AuctionState.cs | 115 ++++ Mimante/src/BidooBidBot/Bidoo/BidooApi.cs | 191 ++++++ .../src/BidooBidBot/Bidoo/BidooReferences.cs | 317 ++++++++++ .../src/BidooBidBot/Bidoo/CatalogClient.cs | 246 ++++++++ .../BidooBidBot/Bidoo/CatalogPageParser.cs | 253 ++++++++ .../BidooBidBot/Bidoo/DataResponseParser.cs | 279 +++++++++ .../src/BidooBidBot/Bidoo/bidoo.default.json | 118 +++- Mimante/src/BidooBidBot/Net/BidLane.cs | 85 +++ Mimante/src/BidooBidBot/Net/BidooTransport.cs | 332 +++++++++++ Mimante/src/BidooBidBot/Net/HttpOutcome.cs | 109 ++++ Mimante/src/BidooBidBot/Net/TokenBucket.cs | 76 +++ Mimante/src/BidooBidBot/Program.cs | 5 +- .../BidooBidBot.Tests/Fixtures/bid-errore.txt | 1 + .../BidooBidBot.Tests/Fixtures/bid-ok.txt | 1 + .../Fixtures/data-conclusa.txt | 1 + .../Fixtures/data-in-corso.txt | 1 + .../BidooBidBot.Tests/Fixtures/data-lista.txt | 1 + .../Fixtures/data-vergine.txt | 1 + .../tests/BidooBidBot.Tests/ProtocolTests.cs | 557 ++++++++++++++++++ 21 files changed, 2870 insertions(+), 3 deletions(-) create mode 100644 Mimante/src/BidooBidBot/Bidoo/AccountParser.cs create mode 100644 Mimante/src/BidooBidBot/Bidoo/AuctionPageParser.cs create mode 100644 Mimante/src/BidooBidBot/Bidoo/AuctionState.cs create mode 100644 Mimante/src/BidooBidBot/Bidoo/BidooApi.cs create mode 100644 Mimante/src/BidooBidBot/Bidoo/BidooReferences.cs create mode 100644 Mimante/src/BidooBidBot/Bidoo/CatalogClient.cs create mode 100644 Mimante/src/BidooBidBot/Bidoo/CatalogPageParser.cs create mode 100644 Mimante/src/BidooBidBot/Bidoo/DataResponseParser.cs create mode 100644 Mimante/src/BidooBidBot/Net/BidLane.cs create mode 100644 Mimante/src/BidooBidBot/Net/BidooTransport.cs create mode 100644 Mimante/src/BidooBidBot/Net/HttpOutcome.cs create mode 100644 Mimante/src/BidooBidBot/Net/TokenBucket.cs create mode 100644 Mimante/tests/BidooBidBot.Tests/Fixtures/bid-errore.txt create mode 100644 Mimante/tests/BidooBidBot.Tests/Fixtures/bid-ok.txt create mode 100644 Mimante/tests/BidooBidBot.Tests/Fixtures/data-conclusa.txt create mode 100644 Mimante/tests/BidooBidBot.Tests/Fixtures/data-in-corso.txt create mode 100644 Mimante/tests/BidooBidBot.Tests/Fixtures/data-lista.txt create mode 100644 Mimante/tests/BidooBidBot.Tests/Fixtures/data-vergine.txt create mode 100644 Mimante/tests/BidooBidBot.Tests/ProtocolTests.cs diff --git a/Mimante/src/BidooBidBot/Bidoo/AccountParser.cs b/Mimante/src/BidooBidBot/Bidoo/AccountParser.cs new file mode 100644 index 0000000..2d87280 --- /dev/null +++ b/Mimante/src/BidooBidBot/Bidoo/AccountParser.cs @@ -0,0 +1,81 @@ +using System.Globalization; + +namespace BidooBidBot.Bidoo; + +/// Ciò che si sa del conto Bidoo. +public sealed record AccountInfo(string? UserId, string? Username, int? RemainingBids, double? ShopCredit); + +/// +/// Legge le pagine del conto: buy_bids.php (pagina intera con utente, saldo e +/// credito), update_credits_status.php (saldo leggero, tre formati osservati), +/// check_auctions_won.php (un numero). Pura, sotto test; le espressioni vengono dai +/// riferimenti. +/// +public static class AccountParser +{ + /// + /// buy_bids.php. Null se la pagina non contiene nessuno dei dati: cookie scaduto o + /// pagina di login. + /// + public static AccountInfo? ParseUserPage(string? html, BidooReferences? refs = null) + { + refs ??= BidooReferences.Default; + var r = refs.Recognizers; + if (string.IsNullOrWhiteSpace(html) || html.Length < 100) return null; + + var id = BidooReferences.FirstGroup(html, r.UserId); + var username = BidooReferences.FirstGroup(html, r.Username); + var bidsText = BidooReferences.FirstGroup(html, r.RemainingBids); + var creditText = BidooReferences.FirstGroup(html, r.ShopCredit); + + int? bids = int.TryParse(bidsText, NumberStyles.Integer, CultureInfo.InvariantCulture, out var b) ? b : null; + double? credit = double.TryParse(creditText, NumberStyles.Float, CultureInfo.InvariantCulture, out var c) ? c : null; + + // Un id «0» o vuoto è la pagina di chi non è collegato. + if (id is "0" or "") id = null; + if (string.IsNullOrWhiteSpace(username)) username = null; + + if (id == null && username == null && bids == null) return null; + return new AccountInfo(id, username, bids, credit); + } + + /// + /// update_credits_status.php?submit=1: un numero, oppure + /// <span id="bids_count">N</span>, oppure utente|puntate|credito|id. + /// + public static AccountInfo? ParseCreditsStatus(string? body, BidooReferences? refs = null) + { + refs ??= BidooReferences.Default; + var text = (body ?? "").Trim(); + if (text.Length == 0) return null; + + if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n)) + return new AccountInfo(null, null, n, null); + + var span = BidooReferences.FirstGroup(text, refs.Recognizers.CreditsCount); + if (int.TryParse(span, NumberStyles.Integer, CultureInfo.InvariantCulture, out n)) + return new AccountInfo(null, null, n, null); + + var parts = text.Split('|'); + if (parts.Length >= 2 && int.TryParse(parts[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var bids)) + { + double? cash = parts.Length >= 3 && double.TryParse(parts[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var c) ? c : null; + var id = parts.Length >= 4 ? parts[3].Trim() : null; + return new AccountInfo(string.IsNullOrEmpty(id) ? null : id, NullIfEmpty(parts[0].Trim()), bids, cash); + } + + return null; + } + + /// + /// Aste vinte da confermare. Null = «non lo so» (errore o pagina di login): deve restare + /// diverso da zero, altrimenti un errore di rete cancellerebbe dalla barra una vincita vera. + /// + public static int? ParseAuctionsWon(string? body) + { + var text = (body ?? "").Trim(); + return int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) && n >= 0 ? n : null; + } + + private static string? NullIfEmpty(string s) => s.Length == 0 ? null : s; +} diff --git a/Mimante/src/BidooBidBot/Bidoo/AuctionPageParser.cs b/Mimante/src/BidooBidBot/Bidoo/AuctionPageParser.cs new file mode 100644 index 0000000..0709980 --- /dev/null +++ b/Mimante/src/BidooBidBot/Bidoo/AuctionPageParser.cs @@ -0,0 +1,103 @@ +using System.Globalization; +using System.Net; + +namespace BidooBidBot.Bidoo; + +/// Quello che la pagina di un'asta dice del prodotto. +public sealed record AuctionPageInfo( + string? Name, double? BuyNowPrice, double? Shipping, string? WinLimit, string? ImageUrl, int? ProductId); + +/// +/// Legge la pagina dell'asta (auction.php?a=…): nome, «Compralo Ora» (il valore di +/// listino), spese di spedizione o di transazione, limite di vincita, foto. Portato da +/// ProductValueCalculator.ExtractProductInfo del legacy; le espressioni stanno nei +/// riferimenti. +/// +public static class AuctionPageParser +{ + public static AuctionPageInfo? Parse(string? html, BidooReferences? refs = null) + { + refs ??= BidooReferences.Default; + var r = refs.Recognizers; + if (string.IsNullOrWhiteSpace(html)) return null; + + string? name = BidooReferences.FirstGroup(html, r.AuctionTitle); + if (name != null) + { + name = CatalogPageParser.DecodeHtml(name); + if (!string.IsNullOrEmpty(r.AuctionTitleSuffix)) + name = name.Replace(r.AuctionTitleSuffix, "", StringComparison.OrdinalIgnoreCase); + name = name.Trim(); + if (name.Length == 0) name = null; + } + + var buyNow = ParsePrice(BidooReferences.FirstGroup(html, r.ProductValue)); + var shipping = ParsePrice(BidooReferences.FirstGroup(html, r.Shipping)); + var winLimit = BidooReferences.FirstGroup(html, r.WinLimit)?.Trim(); + var image = BidooReferences.FirstGroup(html, r.ProductImage); + int? productId = int.TryParse(BidooReferences.FirstGroup(html, r.ProductId), NumberStyles.Integer, CultureInfo.InvariantCulture, out var pid) && pid > 0 ? pid : null; + + if (name == null && buyNow == null && shipping == null && winLimit == null && image == null) return null; + return new AuctionPageInfo(name, buyNow, shipping, string.IsNullOrWhiteSpace(winLimit) ? null : WebUtility.HtmlDecode(winLimit), image, productId); + } + + /// Un prezzo all'italiana («20,00») o col punto. + public static double? ParsePrice(string? text) + { + if (string.IsNullOrWhiteSpace(text)) return null; + var t = text.Trim().Replace(" ", "", StringComparison.Ordinal); + if (t.Contains(',', StringComparison.Ordinal)) t = t.Replace(".", "", StringComparison.Ordinal).Replace(',', '.'); + return double.TryParse(t, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : null; + } +} + +/// +/// Dall'indirizzo di un'asta (o dal solo id) all'id numerico e a un nome provvisorio. +/// Formati: /asta/nome-prodotto-81204324, /asta/81204324, +/// auction.php?a=Galaxy_S25_81204324, oppure l'id nudo. +/// +public static class AuctionUrl +{ + public readonly record struct Parsed(string AuctionId, string? ProductName, string Url); + + public static Parsed? Parse(string? input, BidooReferences? refs = null) + { + refs ??= BidooReferences.Default; + var r = refs.Recognizers; + var text = (input ?? "").Trim(); + if (text.Length == 0) return null; + + if (text.All(char.IsDigit)) + return text.Length >= 5 ? new Parsed(text, null, refs.AuctionPageUrl(text)) : null; + + if (!Uri.TryCreate(text, UriKind.Absolute, out var uri) || !uri.Host.Contains("bidoo", StringComparison.OrdinalIgnoreCase)) + return null; + + foreach (var pattern in r.AuctionIdInPath) + { + var id = BidooReferences.FirstGroup(uri.AbsolutePath, pattern); + if (id != null) return new Parsed(id, NameFromSlug(uri.AbsolutePath.Split('/').LastOrDefault(), id), text); + } + + var a = BidooReferences.FirstGroup(uri.Query, r.AuctionIdInQuery); + if (a != null) + { + a = Uri.UnescapeDataString(a); + var id = BidooReferences.FirstGroup(a, r.AuctionIdDigits); + if (id != null) return new Parsed(id, NameFromSlug(a, id), text); + } + + return null; + } + + /// «Galaxy_S25_Ultra_81204324» o «galaxy-s25-ultra-81204324» → «Galaxy S25 Ultra». + public static string? NameFromSlug(string? slug, string id) + { + if (string.IsNullOrWhiteSpace(slug)) return null; + var s = slug.EndsWith(id, StringComparison.Ordinal) ? slug[..^id.Length] : slug; + s = s.Trim('_', '-', ' ').Replace('_', ' ').Replace('-', ' '); + while (s.Contains(" ", StringComparison.Ordinal)) s = s.Replace(" ", " ", StringComparison.Ordinal); + if (s.Length == 0 || s.All(char.IsDigit) || s.Equals("asta", StringComparison.OrdinalIgnoreCase)) return null; + return CultureInfo.GetCultureInfo("it-IT").TextInfo.ToTitleCase(s.ToLowerInvariant()); + } +} diff --git a/Mimante/src/BidooBidBot/Bidoo/AuctionState.cs b/Mimante/src/BidooBidBot/Bidoo/AuctionState.cs new file mode 100644 index 0000000..efde517 --- /dev/null +++ b/Mimante/src/BidooBidBot/Bidoo/AuctionState.cs @@ -0,0 +1,115 @@ +namespace BidooBidBot.Bidoo; + +/// Stato di un'asta secondo il server. +public enum AuctionStatus +{ + Unknown, + + /// In corso: ON con almeno un puntatore. + Running, + + /// STOP: Bidoo ferma le aste di notte. Non è il nostro «Osserva». + Paused, + + EndedWon, + EndedLost, + + /// ON senza puntate e cronometro corto: sta per cominciare. + Pending, + + /// ON senza puntate e cronometro oltre la soglia: programmata più in là. + Scheduled, + + /// OFF senza vincitore. + Closed +} + +/// Una fotografia dell'asta presa da data.php. +public sealed class AuctionState +{ + public string AuctionId { get; set; } = ""; + public double Timer { get; set; } = 999; + public double Price { get; set; } + public string LastBidder { get; set; } = ""; + public bool IsMyBid { get; set; } + public AuctionStatus Status { get; set; } = AuctionStatus.Unknown; + public DateTime SnapshotTimeUtc { get; set; } = DateTime.UtcNow; + public int PollingLatencyMs { get; set; } + + // ── Materia prima di ServerClock ────────────────────────────────── + + /// Secondo unix dichiarato dal server in questa risposta. + public long ServerUnixSeconds { get; set; } + + /// Secondo unix in cui scade il ciclo, secondo il server. + public long ExpiryUnixSeconds { get; set; } + + /// Tick di Stopwatch alla ricezione (monotono). + public long ReceivedTicks { get; set; } + + // ── Puntate del vincitore (solo ad asta conclusa) ───────────────── + + public int? WinnerBidsPaid { get; set; } + public int? WinnerBidsFree { get; set; } + + /// Il numero che il sito mostra come «Puntate utilizzate». Null se l'asta non è conclusa. + public int? WinnerBidsTotal => + WinnerBidsPaid.HasValue || WinnerBidsFree.HasValue ? (WinnerBidsPaid ?? 0) + (WinnerBidsFree ?? 0) : null; + + /// Le ultime puntate (al massimo 50), dalla più recente. + public List? RecentBidsHistory { get; set; } + + public bool IsTerminal => Status is AuctionStatus.EndedWon or AuctionStatus.EndedLost or AuctionStatus.Closed; +} + +/// Una puntata come la riporta lo storico di data.php. +public sealed class BidHistoryEntry +{ + /// Puntata dell'autopuntata del sito (codice 3). + public const string TypeAuto = "Auto"; + + /// Puntata fatta a mano (codice 1). + public const string TypeManual = "Manuale"; + + /// Il tipo non lo ha detto il server (puntata ricostruita da un cambio di prezzo). + public const string TypeUnknown = ""; + + public decimal Price { get; set; } + public string Username { get; set; } = ""; + + /// Istante unix dichiarato dal server (secondi interi). + public long Timestamp { get; set; } + + public string BidType { get; set; } = TypeUnknown; + public bool IsMyBid { get; set; } + + public bool IsAuto => BidType == TypeAuto; + public bool IsManual => BidType == TypeManual; + + /// Il prezzo in centesimi: su Bidoo è anche il numero d'ordine della puntata nell'asta. + public int PriceCents => (int)Math.Round(Price * 100); +} + +/// Cosa dice bid.php dopo una puntata. +public readonly record struct BidResponse( + bool Ok, + int? PaidRemaining, + int? FreeRemaining, + int? FreeUsedOnAuction, + int? PaidUsedOnAuction, + string? Error, + bool KeepAlive = false) +{ + /// Puntate residue totali: a pagamento più gratuite. + public int? Remaining => PaidRemaining is { } p && FreeRemaining is { } f ? p + f : PaidRemaining; + + /// Puntate usate su questa asta, di entrambi i tipi. + public int? UsedOnAuction => PaidUsedOnAuction is { } p ? p + (FreeUsedOnAuction ?? 0) : FreeUsedOnAuction; +} + +/// Una riga della risposta a più aste (data.php?LISTID=…). +public readonly record struct ListEntry(string AuctionId, string Status, long ExpiryUnix, int PriceCents, string LastBidder, long ServerUnix) +{ + public double Price => PriceCents / 100.0; + public double RemainingSeconds => ServerUnix > 0 && ExpiryUnix > 0 ? Math.Max(0, ExpiryUnix - ServerUnix) : 0; +} diff --git a/Mimante/src/BidooBidBot/Bidoo/BidooApi.cs b/Mimante/src/BidooBidBot/Bidoo/BidooApi.cs new file mode 100644 index 0000000..3b7b040 --- /dev/null +++ b/Mimante/src/BidooBidBot/Bidoo/BidooApi.cs @@ -0,0 +1,191 @@ +using System.Diagnostics; +using System.Globalization; +using BidooBidBot.Net; + +namespace BidooBidBot.Bidoo; + +/// Esito di un'interrogazione di data.php. +public sealed record PollResult(AuctionState? State, HttpOutcome Outcome, string? Error); + +/// Esito di una puntata. +public sealed record BidAttempt( + bool Success, + BidResponse Response, + int LatencyMs, + string? Error, + long SentTicks, + bool UsedFallback, + string RawBody); + +/// +/// Le chiamate a Bidoo (specifica §5): polling, puntata, dati del conto, pagina dell'asta. +/// Gli indirizzi vengono tutti dai riferimenti. Una risposta 403 o la pagina di login al +/// posto dei dati significano sessione non valida: lo si dice con . +/// +public sealed class BidooApi +{ + private readonly BidooTransport _transport; + private readonly BidLane _lane; + private readonly Func _refs; + + public BidooApi(BidooTransport transport, BidLane lane, Func refs) + { + _transport = transport; + _lane = lane; + _refs = refs; + } + + public BidooTransport Transport => _transport; + public BidLane Lane => _lane; + public BidooReferences References => _refs(); + + /// L'utente collegato, per riconoscere le proprie puntate. + public string? Username { get; set; } + + /// La sessione non vale più (403 o pagina di login). Il testo dice cosa si è visto. + public event Action? SessionInvalid; + + private bool CheckSession(HttpOutcome outcome) + { + if (!_transport.HasCookie) return true; + if (outcome.StatusCode == 403) + { + SessionInvalid?.Invoke("Bidoo risponde 403 (accesso negato)"); + return false; + } + if (outcome.Success && DataResponseParser.LooksLikeLoginPage(outcome.Body, _refs())) + { + SessionInvalid?.Invoke("Bidoo risponde con la pagina di login"); + return false; + } + return true; + } + + private string Referer(string auctionId, string? auctionUrl) => + !string.IsNullOrEmpty(auctionUrl) ? auctionUrl! : _refs().AuctionPageUrl(auctionId); + + /// Una interrogazione di data.php per un'asta. + public async Task PollAsync(string auctionId, string? auctionUrl, int maxHistory, CancellationToken ct, + RequestPriority priority = RequestPriority.Normal) + { + var refs = _refs(); + var url = refs.Url(refs.Endpoints.AuctionData, ("id", auctionId)); + var outcome = await _transport.SendAsync(_transport.BuildGet(url, Referer(auctionId, auctionUrl)), priority, ct).ConfigureAwait(false); + + if (!outcome.Success) + { + CheckSession(outcome); + return new PollResult(null, outcome, outcome.Describe()); + } + if (!CheckSession(outcome)) return new PollResult(null, outcome, "sessione non valida"); + + var parsed = DataResponseParser.Parse(auctionId, outcome.Body, outcome.LatencyMs, outcome.ReceivedTicks, + Username, maxHistory, refs); + return new PollResult(parsed.State, outcome, parsed.Error); + } + + /// + /// La puntata: prima sulla corsia dedicata; se questa fallisce per un errore di rete e + /// mancano ancora più di ms, una sola volta sul pool + /// normale (priorità critica). Un «no» di Bidoo non si ritenta mai. + /// + public async Task PlaceBidAsync(string auctionId, string? auctionUrl, Func? msLeft, double retryIfMsLeft, CancellationToken ct) + { + var refs = _refs(); + var url = refs.Url(refs.Endpoints.Bid, ("id", auctionId)); + var referer = Referer(auctionId, auctionUrl); + + var outcome = await _lane.SendBidAsync(url, referer, ct).ConfigureAwait(false); + var fallback = false; + + if (outcome.IsNetworkError && msLeft != null && msLeft() > retryIfMsLeft) + { + fallback = true; + var request = _transport.BuildGet(url, referer); + request.Headers.TryAddWithoutValidation("Origin", refs.BaseUrl); + outcome = await _transport.SendAsync(request, RequestPriority.Critical, ct).ConfigureAwait(false); + } + + CheckSession(outcome); + + var parsed = DataResponseParser.ParseBidResponse(outcome.Body); + string? error = null; + if (!parsed.Ok) + { + error = outcome.Body.Length == 0 ? outcome.Describe() : parsed.Error; + if (outcome.StatusCode is >= 400) error = $"HTTP {outcome.StatusCode}: {error}"; + } + + return new BidAttempt(parsed.Ok, parsed, outcome.LatencyMs, error, outcome.SentTicks, fallback, outcome.Body); + } + + /// buy_bids.php: utente, saldo, credito. Null se la sessione non vale. + public async Task GetUserInfoAsync(CancellationToken ct) + { + var refs = _refs(); + var outcome = await _transport.SendAsync( + _transport.BuildGet(refs.Url(refs.Endpoints.UserInfo), refs.BaseUrl + "/", ajax: false), RequestPriority.Background, ct).ConfigureAwait(false); + if (!outcome.Success) + { + CheckSession(outcome); + return null; + } + + var info = AccountParser.ParseUserPage(outcome.Body, refs); + if (info?.Username == null && _transport.HasCookie && DataResponseParser.LooksLikeLoginPage(outcome.Body, refs)) + { + SessionInvalid?.Invoke("la pagina del conto chiede di accedere"); + return null; + } + return info; + } + + /// update_credits_status.php: il saldo leggero. + public async Task GetCreditsAsync(CancellationToken ct) + { + var refs = _refs(); + var outcome = await _transport.SendAsync( + _transport.BuildGet(refs.Url(refs.Endpoints.CreditsStatus)), RequestPriority.Background, ct).ConfigureAwait(false); + if (!outcome.Success || !CheckSession(outcome)) return null; + return AccountParser.ParseCreditsStatus(outcome.Body, refs); + } + + /// Aste vinte da confermare. Null = non lo so. + public async Task GetAuctionsWonAsync(CancellationToken ct) + { + var refs = _refs(); + var outcome = await _transport.SendAsync( + _transport.BuildGet(refs.Url(refs.Endpoints.AuctionsWon)), RequestPriority.Background, ct).ConfigureAwait(false); + return outcome.Success ? AccountParser.ParseAuctionsWon(outcome.Body) : null; + } + + /// La pagina dell'asta: nome, Compralo Ora, spedizione, limite di vincita, foto. + public async Task GetAuctionPageAsync(string auctionId, string? auctionUrl, CancellationToken ct) + { + var refs = _refs(); + var url = !string.IsNullOrEmpty(auctionUrl) && auctionUrl!.StartsWith(refs.BaseUrl, StringComparison.OrdinalIgnoreCase) + ? auctionUrl + : refs.AuctionPageUrl(auctionId); + var outcome = await _transport.SendAsync(_transport.BuildGet(url, refs.BaseUrl + "/", ajax: false), RequestPriority.Background, ct).ConfigureAwait(false); + return outcome.Success ? AuctionPageParser.Parse(outcome.Body, refs) : null; + } + + /// Stati di molte aste in una richiesta (data.php?LISTID=…). + public async Task> GetListAsync(IReadOnlyList auctionIds, CancellationToken ct) + { + var refs = _refs(); + var result = new List(); + foreach (var chunk in auctionIds.Chunk(Math.Max(1, refs.Limits.BulkPricesChunk))) + { + var url = refs.Url(refs.Endpoints.BulkPrices, + ("ids", string.Join(',', chunk)), + ("unixMs", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture))); + var outcome = await _transport.SendAsync(_transport.BuildGet(url), RequestPriority.Background, ct).ConfigureAwait(false); + if (outcome.Success) result.AddRange(DataResponseParser.ParseList(outcome.Body, refs)); + } + return result; + } + + /// Millisecondi trascorsi da un tick di Stopwatch. + public static double MsSince(long ticks) => (Stopwatch.GetTimestamp() - ticks) * 1000.0 / Stopwatch.Frequency; +} diff --git a/Mimante/src/BidooBidBot/Bidoo/BidooReferences.cs b/Mimante/src/BidooBidBot/Bidoo/BidooReferences.cs new file mode 100644 index 0000000..f801f81 --- /dev/null +++ b/Mimante/src/BidooBidBot/Bidoo/BidooReferences.cs @@ -0,0 +1,317 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using BidooBidBot.Logging; + +namespace BidooBidBot.Bidoo; + +/// +/// I riferimenti del sito (specifica §5, Appendice E): indirizzi, intestazioni, espressioni +/// per leggere le pagine, costanti del protocollo. Nessuna classe contiene stringhe di +/// endpoint: tutto passa di qui, così un cambiamento di Bidoo si corregge nel file +/// /config/riferimenti/bidoo.json senza ricompilare. +/// +public sealed class BidooReferences +{ + public string BaseUrl { get; set; } = ""; + public string UserAgent { get; set; } = ""; + public string DefaultUserAgent { get; set; } = ""; + public EndpointSet Endpoints { get; set; } = new(); + public HeaderSet Headers { get; set; } = new(); + public RecognizerSet Recognizers { get; set; } = new(); + public TimingSet Timing { get; set; } = new(); + public LimitSet Limits { get; set; } = new(); + public ParsingSet Parsing { get; set; } = new(); + + public sealed class EndpointSet + { + public string AuctionData { get; set; } = ""; + public string Bid { get; set; } = ""; + public string BulkPrices { get; set; } = ""; + public string UserInfo { get; set; } = ""; + public string CreditsStatus { get; set; } = ""; + public string AuctionsWon { get; set; } = ""; + public string CatalogFirstPage { get; set; } = ""; + public string CatalogNextPage { get; set; } = ""; + public string CatalogNextPageBody { get; set; } = ""; + public string CatalogLegacy { get; set; } = ""; + public string Home { get; set; } = "/"; + public string AuctionPage { get; set; } = ""; + public string AuctionPageSlug { get; set; } = ""; + public string Login { get; set; } = ""; + public string WarmUp { get; set; } = ""; + } + + public sealed class HeaderSet + { + public string AjaxAccept { get; set; } = "*/*"; + public string DocumentAccept { get; set; } = ""; + public string XRequestedWith { get; set; } = "XMLHttpRequest"; + public string AcceptLanguage { get; set; } = ""; + } + + public sealed class RecognizerSet + { + public string UserId { get; set; } = ""; + public string Username { get; set; } = ""; + public List RemainingBids { get; set; } = new(); + public string ShopCredit { get; set; } = ""; + public string CreditsCount { get; set; } = ""; + public List LoginPageMarkers { get; set; } = new(); + public string SessionCookie { get; set; } = "__stattrb"; + public string AuctionTitle { get; set; } = ""; + public string AuctionTitleSuffix { get; set; } = ""; + public List ProductValue { get; set; } = new(); + public List Shipping { get; set; } = new(); + public string WinLimit { get; set; } = ""; + public string ProductImage { get; set; } = ""; + public string ProductId { get; set; } = ""; + public string CatalogCard { get; set; } = ""; + public string CatalogDataUrl { get; set; } = ""; + public string CatalogDataFreq { get; set; } = ""; + public string CatalogDataCredit { get; set; } = ""; + public string CatalogDataCreditValue { get; set; } = ""; + public string CatalogDataProduct { get; set; } = ""; + public string CatalogImage { get; set; } = ""; + public string CatalogName { get; set; } = ""; + public string CatalogBuyNow { get; set; } = ""; + public string CatalogManualOnlyMarker { get; set; } = ""; + public string CatalogCategory { get; set; } = ""; + public List AuctionIdInPath { get; set; } = new(); + public string AuctionIdInQuery { get; set; } = ""; + public string AuctionIdDigits { get; set; } = ""; + } + + public sealed class TimingSet + { + public int PreCheckMs { get; set; } = 60; + public double CriticalWindowS { get; set; } = 4; + public double ScheduledIfTimerAboveS { get; set; } = 1800; + } + + public sealed class LimitSet + { + public int MaxConcurrency { get; set; } = 24; + public int BidLaneConnections { get; set; } = 3; + public int BidLaneKeepAliveSeconds { get; set; } = 20; + public int BidTimeoutMs { get; set; } = 3000; + public int RequestTimeoutMs { get; set; } = 8000; + public int BrakeMinMs { get; set; } = 1000; + public int BrakeMaxMs { get; set; } = 8000; + public int HistoryMaxEntries { get; set; } = 50; + public int BulkPricesChunk { get; set; } = 60; + public int CatalogPageSize { get; set; } = 50; + public int CatalogMaxPages { get; set; } = 200; + } + + public sealed class ParsingSet + { + public string CoreSeparator { get; set; } = ";"; + public string HistorySeparator { get; set; } = "|"; + public string CoreHistorySeparator { get; set; } = ","; + public string ListSeparator { get; set; } = "#"; + public string BidTypeManual { get; set; } = "1"; + public string BidTypeAuto { get; set; } = "3"; + public string StatusOn { get; set; } = "ON"; + public string StatusOff { get; set; } = "OFF"; + public string StatusStop { get; set; } = "STOP"; + } + + // ── Comodità ───────────────────────────────────────────────────────── + + /// Indirizzo completo da un modello con segnaposto {id}, {ids}… + public string Url(string template, params (string Key, string Value)[] values) => + BaseUrl.TrimEnd('/') + Fill(template, values); + + public static string Fill(string template, params (string Key, string Value)[] values) + { + var text = template; + foreach (var (key, value) in values) + text = text.Replace("{" + key + "}", value, StringComparison.Ordinal); + return text; + } + + public string AuctionPageUrl(string auctionId) => Url(Endpoints.AuctionPage, ("id", auctionId)); + + /// Lo User-Agent da usare: quello del file, quello della sessione, o quello di ripiego. + public string EffectiveUserAgent(string? sessionUserAgent) => + !string.IsNullOrWhiteSpace(UserAgent) ? UserAgent + : !string.IsNullOrWhiteSpace(sessionUserAgent) ? sessionUserAgent! + : DefaultUserAgent; + + // ── Espressioni ────────────────────────────────────────────────────── + + private static readonly ConcurrentDictionary RegexCache = new(StringComparer.Ordinal); + + /// + /// L'espressione compilata per un modello del file. Tutte senza distinzione di maiuscole + /// e con il punto che attraversa gli a capo; un modello sbagliato non fa cadere nulla + /// (restituisce un'espressione che non trova niente). + /// + public static Regex Rx(string pattern) + { + if (string.IsNullOrEmpty(pattern)) return NeverMatch; + return RegexCache.GetOrAdd(pattern, p => + { + try + { + return new Regex(p, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled, + TimeSpan.FromMilliseconds(250)); + } + catch (ArgumentException) + { + return NeverMatch; + } + }); + } + + private static readonly Regex NeverMatch = new("(?!)", RegexOptions.Compiled); + + /// Il primo gruppo della prima espressione che trova qualcosa. + public static string? FirstGroup(string? text, IEnumerable patterns) + { + if (string.IsNullOrEmpty(text)) return null; + foreach (var p in patterns) + { + try + { + var m = Rx(p).Match(text); + if (m.Success && m.Groups.Count > 1) return m.Groups[1].Value; + } + catch (RegexMatchTimeoutException) { /* pagina patologica: si passa alla prossima */ } + } + return null; + } + + public static string? FirstGroup(string? text, string pattern) => FirstGroup(text, new[] { pattern }); + + // ── Caricamento ────────────────────────────────────────────────────── + + public static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + ReadCommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true, + WriteIndented = true + }; + + private static readonly JsonDocumentOptions DocOptions = new() + { + CommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true + }; + + /// Il testo dei valori di fabbrica incorporati nel binario. + public static string DefaultJson() + { + using var stream = typeof(BidooReferences).Assembly.GetManifestResourceStream("bidoo.default.json") + ?? throw new InvalidOperationException("valori di fabbrica di bidoo.json mancanti dal binario"); + using var reader = new StreamReader(stream); + return reader.ReadToEnd(); + } + + private static readonly Lazy LazyDefault = new(() => Parse(null)); + + /// I valori di fabbrica, senza file: per i test e per chi non ha ancora /config. + public static BidooReferences Default => LazyDefault.Value; + + /// + /// Fabbrica più file: il file può contenere solo le voci da cambiare, il resto resta di + /// fabbrica. Commenti e virgole finali ammessi. Un file illeggibile solleva un errore + /// (chi carica tiene la versione precedente e lo scrive nel registro). + /// + public static BidooReferences Parse(string? overrideJson) + { + var baseNode = JsonNode.Parse(DefaultJson(), documentOptions: DocOptions)!.AsObject(); + if (!string.IsNullOrWhiteSpace(overrideJson)) + { + var over = JsonNode.Parse(overrideJson, documentOptions: DocOptions) as JsonObject + ?? throw new JsonException("il file deve contenere un oggetto JSON"); + Merge(baseNode, over); + } + return baseNode.Deserialize(JsonOptions)!; + } + + /// Unione profonda: gli oggetti si fondono, tutto il resto (liste comprese) si sostituisce. + private static void Merge(JsonObject target, JsonObject source) + { + foreach (var (key, value) in source.ToList()) + { + var match = target.FirstOrDefault(kv => string.Equals(kv.Key, key, StringComparison.OrdinalIgnoreCase)).Key ?? key; + if (value is JsonObject so && target[match] is JsonObject to) Merge(to, so); + else target[match] = value?.DeepClone(); + } + } +} + +/// +/// Tiene i riferimenti in vigore e li rilegge quando il file cambia (controllo ogni 5 s). +/// Se il file manca lo crea con i valori di fabbrica, così l'utente ha qualcosa da +/// correggere; se un file modificato non si legge, resta la versione precedente e il +/// registro dice perché. +/// +public sealed class ReferencesProvider : IDisposable +{ + private readonly string _file; + private readonly AppLog? _log; + private readonly Timer? _timer; + private DateTime _lastWrite = DateTime.MinValue; + private volatile BidooReferences _current; + + public ReferencesProvider(string folder, AppLog? log, bool watch = true) + { + _file = Path.Combine(folder, "bidoo.json"); + _log = log; + _current = BidooReferences.Default; + + try + { + if (!File.Exists(_file)) + { + Directory.CreateDirectory(folder); + File.WriteAllText(_file, BidooReferences.DefaultJson()); + } + } + catch (Exception ex) + { + log?.Warn("RIFERIMENTI", $"Impossibile scrivere {_file}: uso i valori di fabbrica ({ex.Message})"); + } + + Reload(initial: true); + if (watch) _timer = new Timer(_ => Reload(initial: false), null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)); + } + + public BidooReferences Current => _current; + + /// Scatta quando un file modificato è stato letto e applicato. + public event Action? Changed; + + public string FilePath => _file; + + private void Reload(bool initial) + { + try + { + if (!File.Exists(_file)) return; + var stamp = File.GetLastWriteTimeUtc(_file); + if (stamp == _lastWrite) return; + _lastWrite = stamp; + + var refs = BidooReferences.Parse(File.ReadAllText(_file)); + _current = refs; + if (!initial) + { + _log?.Info("RIFERIMENTI", $"bidoo.json riletto: indirizzi ed espressioni aggiornati (modificato alle {AppInfo.ToLocal(stamp).ToString("HH:mm:ss", CultureInfo.InvariantCulture)})"); + Changed?.Invoke(refs); + } + } + catch (Exception ex) + { + _log?.Error("RIFERIMENTI", $"bidoo.json non leggibile, resta la versione precedente: {ex.Message}"); + } + } + + public void Dispose() => _timer?.Dispose(); +} diff --git a/Mimante/src/BidooBidBot/Bidoo/CatalogClient.cs b/Mimante/src/BidooBidBot/Bidoo/CatalogClient.cs new file mode 100644 index 0000000..689443e --- /dev/null +++ b/Mimante/src/BidooBidBot/Bidoo/CatalogClient.cs @@ -0,0 +1,246 @@ +using System.Globalization; +using BidooBidBot.Logging; +using BidooBidBot.Net; + +namespace BidooBidBot.Bidoo; + +/// +/// Il catalogo pubblico di Bidoo (portato da Services/BidooCatalogClient del legacy): +/// categorie, listato paginato a scorrimento, aggiornamento prezzi in massa. Non richiede +/// l'accesso. +/// +/// La paginazione del sito: prima pagina GET get_auctions.php?tab=T&tag=G, +/// seguenti POST get_auction_updates.php con view = tutti gli id già visti. +/// Niente numero di pagina né cursore: la fine si riconosce solo da una pagina vuota. +/// +public sealed class CatalogClient +{ + private readonly BidooTransport _http; + private readonly Func _refs; + private readonly AppLog? _log; + private readonly Dictionary Auctions)> _cache = new(StringComparer.Ordinal); + private readonly Dictionary _lastReported = new(StringComparer.Ordinal); + private List? _categories; + private DateTime _categoriesAt = DateTime.MinValue; + + public CatalogClient(BidooTransport http, Func refs, AppLog? log) + { + _http = http; + _refs = refs; + _log = log; + } + + public static readonly IReadOnlyList SpecialCategories = new[] + { + CatalogCategory.AllAuctions, + new CatalogCategory(1, 0, "", "Aste di puntate", true), + new CatalogCategory(5, 0, "", "Aste manuali", true) + }; + + /// Le categorie di ripiego, se la pagina principale non si legge. + public static readonly IReadOnlyList DefaultCategories = new[] + { + new CatalogCategory(4, 6, "buoni", "Buoni", false), + new CatalogCategory(4, 5, "smartphone", "Smartphone", false), + new CatalogCategory(4, 7, "apple", "Apple", false), + new CatalogCategory(4, 13, "bellezza", "Bellezza", false), + new CatalogCategory(4, 8, "cucina", "Cucina", false), + new CatalogCategory(4, 18, "casa_e_giardino", "Casa e giardino", false), + new CatalogCategory(4, 11, "elettrodomestici", "Elettrodomestici", false), + new CatalogCategory(4, 9, "videogame", "Videogame", false), + new CatalogCategory(4, 41, "giocattoli", "Giocattoli", false), + new CatalogCategory(4, 14, "tablet-e-pc", "Tablet e PC", false), + new CatalogCategory(4, 20, "hobby", "Hobby", false), + new CatalogCategory(4, 22, "smartwatch", "Smartwatch", false), + new CatalogCategory(4, 12, "moda", "Moda", false), + new CatalogCategory(4, 10, "smart-tv", "Smart TV", false), + new CatalogCategory(4, 21, "fai_da_te", "Fai da te", false), + new CatalogCategory(4, 26, "luxury", "Luxury", false), + new CatalogCategory(4, 19, "cuffie-e-audio", "Cuffie e audio", false), + new CatalogCategory(4, 38, "prima-infanzia", "Prima infanzia", false) + }; + + public async Task> GetCategoriesAsync(bool forceRefresh, CancellationToken ct) + { + lock (_cache) + { + if (!forceRefresh && _categories != null && DateTime.UtcNow - _categoriesAt < TimeSpan.FromMinutes(30)) + return _categories.ToList(); + } + + var refs = _refs(); + var list = new List(SpecialCategories); + try + { + var outcome = await _http.SendAsync(_http.BuildGet(refs.Url(refs.Endpoints.Home), ajax: false), RequestPriority.Background, ct).ConfigureAwait(false); + if (outcome.Success) list.AddRange(CatalogPageParser.ParseCategories(outcome.Body, refs)); + else _log?.Warn("CATALOGO", $"Pagina principale non raggiungibile ({outcome.Describe()}): elenco categorie predefinito"); + } + catch (OperationCanceledException) { throw; } + catch { /* si ricade sull'elenco predefinito */ } + + if (list.Count <= SpecialCategories.Count) list.AddRange(DefaultCategories); + + lock (_cache) + { + _categories = list; + _categoriesAt = DateTime.UtcNow; + } + return list.ToList(); + } + + public void InvalidateCache() + { + lock (_cache) _cache.Clear(); + } + + /// + /// Fino a aste della categoria, pagina dopo pagina. Il + /// listato è in ordine di scadenza: fermarsi al tetto non taglia nulla di urgente. + /// + public async Task> GetAllAuctionsAsync(CatalogCategory category, int maxAuctions, int cacheSeconds, CancellationToken ct) + { + if (cacheSeconds > 0) + { + lock (_cache) + { + if (_cache.TryGetValue(category.Key, out var hit) && hit.Auctions.Count > 0 && + DateTime.UtcNow - hit.At < TimeSpan.FromSeconds(cacheSeconds)) + return hit.Auctions.ToList(); + } + } + + var all = new List(); + var seen = new HashSet(StringComparer.Ordinal); + + if (!await CollectPagesAsync(category, all, seen, maxAuctions, ct).ConfigureAwait(false)) + { + _log?.Warn("CATALOGO", $"\"{category.DisplayName}\": paginazione non disponibile, uso il listato classico"); + await CollectLegacyAsync(category, all, seen, maxAuctions, ct).ConfigureAwait(false); + } + + if (cacheSeconds > 0 && all.Count > 0) + { + lock (_cache) _cache[category.Key] = (DateTime.UtcNow, all.ToList()); + } + + lock (_lastReported) + { + if (!_lastReported.TryGetValue(category.Key, out var before) || before != all.Count) + { + _lastReported[category.Key] = all.Count; + _log?.Debug("CATALOGO", $"\"{category.DisplayName}\": {all.Count} aste"); + } + } + return all; + } + + private async Task CollectPagesAsync(CatalogCategory category, List all, HashSet seen, int maxAuctions, CancellationToken ct) + { + var refs = _refs(); + var tab = (category.IsSpecial ? category.TabId : 4).ToString(CultureInfo.InvariantCulture); + var tag = (category.IsSpecial ? 0 : category.TagId).ToString(CultureInfo.InvariantCulture); + var view = new List(); + var pageSize = Math.Max(1, refs.Limits.CatalogPageSize); + var pageLimit = Math.Min(refs.Limits.CatalogMaxPages, (maxAuctions + pageSize - 1) / pageSize + 2); + + for (var page = 0; page < pageLimit; page++) + { + ct.ThrowIfCancellationRequested(); + + var request = page == 0 + ? _http.BuildGet(refs.Url(refs.Endpoints.CatalogFirstPage, ("tab", tab), ("tag", tag)), refs.BaseUrl + "/") + : _http.BuildPost(refs.Url(refs.Endpoints.CatalogNextPage), + BidooReferences.Fill(refs.Endpoints.CatalogNextPageBody, ("view", string.Join(',', view)), ("tab", tab), ("tag", tag)), + refs.BaseUrl + "/"); + + var outcome = await _http.SendAsync(request, RequestPriority.Background, ct).ConfigureAwait(false); + if (!outcome.Success) + { + if (page == 0) + { + _log?.Warn("CATALOGO", $"\"{category.DisplayName}\": {outcome.Describe()}"); + return false; + } + break; + } + + var parsed = CatalogPageParser.ParsePage(outcome.Body, refs); + if (parsed == null) + { + if (page == 0) return false; + break; + } + if (parsed.Ids.Count == 0) break; // in fondo al listato + + var added = 0; + foreach (var auction in parsed.Auctions) + { + if (!seen.Add(auction.AuctionId)) continue; + all.Add(auction); + added++; + } + + // Tutti gli id, anche quelli delle schede non capite: dicono al server dove eravamo. + view.AddRange(parsed.Ids); + + if (all.Count >= maxAuctions) break; + if (added == 0) break; // il server ha smesso di avanzare + } + return all.Count > 0; + } + + private async Task CollectLegacyAsync(CatalogCategory category, List all, HashSet seen, int maxAuctions, CancellationToken ct) + { + var refs = _refs(); + var tab = (category.IsSpecial ? category.TabId : 4).ToString(CultureInfo.InvariantCulture); + var tag = (category.IsSpecial ? 0 : category.TagId).ToString(CultureInfo.InvariantCulture); + var url = refs.Url(refs.Endpoints.CatalogLegacy, ("tab", tab), ("tag", tag)); + + for (var round = 0; round < 4 && all.Count < maxAuctions; round++) + { + ct.ThrowIfCancellationRequested(); + var outcome = await _http.SendAsync(_http.BuildGet(url, refs.BaseUrl + "/"), RequestPriority.Background, ct).ConfigureAwait(false); + if (!outcome.Success) return; + + var added = 0; + foreach (var auction in CatalogPageParser.ParseAuctions(outcome.Body, refs)) + { + if (!seen.Add(auction.AuctionId)) continue; + all.Add(auction); + added++; + if (all.Count >= maxAuctions) return; + } + if (added == 0) return; + } + } + + /// Prezzo, ultimo puntatore e timer di molte aste, a blocchi (60 per richiesta). + public async Task UpdateStatesAsync(IReadOnlyList auctions, CancellationToken ct) + { + if (auctions.Count == 0) return; + var refs = _refs(); + var byId = auctions.GroupBy(a => a.AuctionId).ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal); + + foreach (var chunk in auctions.Chunk(Math.Max(1, refs.Limits.BulkPricesChunk))) + { + var url = refs.Url(refs.Endpoints.BulkPrices, + ("ids", string.Join(',', chunk.Select(a => a.AuctionId))), + ("unixMs", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture))); + + var outcome = await _http.SendAsync(_http.BuildGet(url, refs.BaseUrl + "/"), RequestPriority.Background, ct).ConfigureAwait(false); + if (!outcome.Success) continue; + + foreach (var e in DataResponseParser.ParseList(outcome.Body, refs)) + { + if (!byId.TryGetValue(e.AuctionId, out var a)) continue; + a.CurrentPrice = e.PriceCents / 100m; + if (e.LastBidder.Length > 0) a.LastBidder = e.LastBidder; + a.RemainingSeconds = (int)e.RemainingSeconds; + a.Status = e.Status; + a.IsActive = e.Status == refs.Parsing.StatusOn; + a.LastUpdatedUtc = DateTime.UtcNow; + } + } + } +} diff --git a/Mimante/src/BidooBidBot/Bidoo/CatalogPageParser.cs b/Mimante/src/BidooBidBot/Bidoo/CatalogPageParser.cs new file mode 100644 index 0000000..6c626c8 --- /dev/null +++ b/Mimante/src/BidooBidBot/Bidoo/CatalogPageParser.cs @@ -0,0 +1,253 @@ +using System.Globalization; +using System.Net; +using System.Text; +using System.Text.Json; + +namespace BidooBidBot.Bidoo; + +/// Un'asta come compare nel catalogo pubblico di Bidoo. +public sealed class CatalogAuction +{ + public string AuctionId { get; set; } = ""; + public string Name { get; set; } = ""; + public string Url { get; set; } = ""; + public string? ImageUrl { get; set; } + public decimal CurrentPrice { get; set; } + public decimal? BuyNowPrice { get; set; } + public string LastBidder { get; set; } = ""; + public int RemainingSeconds { get; set; } + public int TimerFrequency { get; set; } + public bool IsActive { get; set; } = true; + public string Status { get; set; } = ""; + public bool IsCreditAuction { get; set; } + public int CreditValue { get; set; } + public bool IsManualOnly { get; set; } + public int ProductId { get; set; } + public DateTime LastUpdatedUtc { get; set; } = DateTime.UtcNow; +} + +/// Categoria del catalogo: le tre speciali (tab) e quelle per tag. +public sealed record CatalogCategory(int TabId, int TagId, string Slug, string DisplayName, bool IsSpecial) +{ + /// Chiave stabile per cache e interfaccia. + public string Key => IsSpecial ? $"s{TabId}" : $"t{TagId}"; + + public static readonly CatalogCategory AllAuctions = new(3, 0, "", "Tutte le aste", true); +} + +/// Una pagina di listato: le schede interpretate e gli id così come arrivano. +public sealed record CatalogPage(List Auctions, List Ids); + +/// +/// Interpreta le risposte del listato (portato dal legacy). Le due chiamate hanno la stessa +/// struttura con nomi diversi: schede in content (prima pagina) o items +/// (successive), attributi in auctions_attributes o attributes, id sempre in +/// list. Distingue «pagina vuota, siamo in fondo» da «risposta incomprensibile». +/// +public static class CatalogPageParser +{ + public static CatalogPage? ParsePage(string? body, BidooReferences? refs = null) + { + refs ??= BidooReferences.Default; + if (string.IsNullOrWhiteSpace(body)) return null; + + try + { + using var document = JsonDocument.Parse(body); + var root = document.RootElement; + + if (root.ValueKind != JsonValueKind.Object) return null; + if (!root.TryGetProperty("list", out var list) || list.ValueKind != JsonValueKind.Array) return null; + + var ids = new List(list.GetArrayLength()); + foreach (var element in list.EnumerateArray()) + { + var id = element.ValueKind == JsonValueKind.String ? element.GetString() : element.GetRawText(); + if (!string.IsNullOrWhiteSpace(id)) ids.Add(id!); + } + + var html = new StringBuilder(); + if (TryGetArray(root, "content", out var cards) || TryGetArray(root, "items", out cards)) + { + foreach (var card in cards.EnumerateArray()) + { + if (card.ValueKind != JsonValueKind.String) continue; + html.Append(card.GetString()).Append('\n'); + } + } + + var auctions = ParseAuctions(html.ToString(), refs); + + if (TryGetObject(root, "auctions_attributes", out var attributes) || TryGetObject(root, "attributes", out attributes)) + ApplyAttributes(auctions, attributes, refs); + + return new CatalogPage(auctions, ids); + } + catch (JsonException) + { + return null; + } + } + + private static bool TryGetArray(JsonElement root, string name, out JsonElement value) => + root.TryGetProperty(name, out value) && value.ValueKind == JsonValueKind.Array; + + private static bool TryGetObject(JsonElement root, string name, out JsonElement value) => + root.TryGetProperty(name, out value) && value.ValueKind == JsonValueKind.Object; + + /// I valori strutturati vincono su quelli letti dal markup. + private static void ApplyAttributes(List auctions, JsonElement attributes, BidooReferences refs) + { + foreach (var auction in auctions) + { + if (!attributes.TryGetProperty(auction.AuctionId, out var a) || a.ValueKind != JsonValueKind.Object) continue; + + if (TryReadInt(a, "data-freq", out var frequency) && frequency > 0) auction.TimerFrequency = frequency; + if (TryReadInt(a, "data-credit", out var credit)) auction.IsCreditAuction = credit == 1; + if (TryReadInt(a, "data-credit-value", out var creditValue)) auction.CreditValue = creditValue; + if (TryReadInt(a, "data-id-product", out var productId) && productId > 0) auction.ProductId = productId; + + if (a.TryGetProperty("data-url", out var slug) && slug.ValueKind == JsonValueKind.String && + !string.IsNullOrWhiteSpace(slug.GetString())) + { + auction.Url = refs.Url(refs.Endpoints.AuctionPageSlug, ("slug", slug.GetString()!)); + } + } + } + + private static bool TryReadInt(JsonElement owner, string name, out int value) + { + value = 0; + if (!owner.TryGetProperty(name, out var p)) return false; + return p.ValueKind switch + { + JsonValueKind.Number => p.TryGetInt32(out value), + JsonValueKind.String => int.TryParse(p.GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out value), + _ => false + }; + } + + /// Le schede da un blocco di HTML (listato o vecchia pagina intera). + public static List ParseAuctions(string html, BidooReferences? refs = null) + { + refs ??= BidooReferences.Default; + var r = refs.Recognizers; + var auctions = new List(); + var seen = new HashSet(StringComparer.Ordinal); + + var matches = BidooReferences.Rx(r.CatalogCard).Matches(html); + for (var i = 0; i < matches.Count; i++) + { + var match = matches[i]; + var id = match.Groups[1].Value; + if (!seen.Add(id)) continue; + + var start = match.Index; + var end = i + 1 < matches.Count ? matches[i + 1].Index : Math.Min(html.Length, start + 6000); + var auction = ParseSingle(id, html[start..end], refs); + if (auction != null) auctions.Add(auction); + } + return auctions; + } + + private static CatalogAuction? ParseSingle(string id, string block, BidooReferences refs) + { + var r = refs.Recognizers; + try + { + var auction = new CatalogAuction { AuctionId = id }; + + var slug = BidooReferences.FirstGroup(block, r.CatalogDataUrl); + auction.Url = slug != null + ? refs.Url(refs.Endpoints.AuctionPageSlug, ("slug", slug)) + : refs.AuctionPageUrl(id); + + if (int.TryParse(BidooReferences.FirstGroup(block, r.CatalogDataFreq), out var freq)) auction.TimerFrequency = freq; + auction.IsCreditAuction = BidooReferences.FirstGroup(block, r.CatalogDataCredit) == "1"; + if (int.TryParse(BidooReferences.FirstGroup(block, r.CatalogDataCreditValue), out var cv)) auction.CreditValue = cv; + if (int.TryParse(BidooReferences.FirstGroup(block, r.CatalogDataProduct), out var pid)) auction.ProductId = pid; + auction.ImageUrl = BidooReferences.FirstGroup(block, r.CatalogImage); + + var name = BidooReferences.FirstGroup(block, r.CatalogName); + auction.Name = name != null ? DecodeHtml(name) : ""; + if (string.IsNullOrWhiteSpace(auction.Name)) auction.Name = $"Asta {id}"; + + if (TryParsePrice(BidooReferences.FirstGroup(block, r.CatalogBuyNow), out var buyNow)) auction.BuyNowPrice = buyNow; + + auction.IsManualOnly = r.CatalogManualOnlyMarker.Length > 0 && + block.Contains(r.CatalogManualOnlyMarker, StringComparison.OrdinalIgnoreCase); + auction.CurrentPrice = 0.01m; + auction.RemainingSeconds = auction.TimerFrequency; + return auction; + } + catch + { + return null; + } + } + + /// + /// Prezzo all'italiana: il punto si toglie solo quando è davvero un separatore di migliaia + /// (c'è anche una virgola, o raggruppa cifre a tre a tre); «14.00» resta quattordici. + /// + public static bool TryParsePrice(string? raw, out decimal value) + { + value = 0; + if (string.IsNullOrWhiteSpace(raw)) return false; + var text = raw.Trim(); + + if (text.Contains(',', StringComparison.Ordinal)) + text = text.Replace(".", "", StringComparison.Ordinal).Replace(',', '.'); + else if (IsThousands(text)) + text = text.Replace(".", "", StringComparison.Ordinal); + + return decimal.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value); + } + + private static bool IsThousands(string text) + { + var groups = text.Split('.'); + if (groups.Length < 2 || groups[0].Length is < 1 or > 3 || !groups[0].All(char.IsDigit)) return false; + return groups.Skip(1).All(g => g.Length == 3 && g.All(char.IsDigit)); + } + + /// Entità HTML 4 più quelle HTML5 che compaiono nei nomi (&dash;, &plus;…). + private static readonly (string Entity, string Replacement)[] Html5Entities = + { + ("‐", "-"), ("+", "+"), ("!", "!"), ("?", "?"), + (".", "."), (",", ","), (":", ":"), (";", ";"), + ("(", "("), (")", ")"), ("/", "/"), ("*", "*"), + ("@", "@"), ("#", "#"), ("%", "%") + }; + + public static string DecodeHtml(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) return ""; + var text = WebUtility.HtmlDecode(raw); + if (text.Contains('&', StringComparison.Ordinal)) + { + foreach (var (entity, replacement) in Html5Entities) + if (text.Contains(entity, StringComparison.OrdinalIgnoreCase)) + text = text.Replace(entity, replacement, StringComparison.OrdinalIgnoreCase); + if (text.Contains('&', StringComparison.Ordinal)) text = WebUtility.HtmlDecode(text); + } + return text.Trim(); + } + + /// Le categorie per tag dalla pagina principale. + public static List ParseCategories(string? html, BidooReferences? refs = null) + { + refs ??= BidooReferences.Default; + var list = new List(); + if (string.IsNullOrEmpty(html)) return list; + + foreach (System.Text.RegularExpressions.Match m in BidooReferences.Rx(refs.Recognizers.CatalogCategory).Matches(html)) + { + if (!int.TryParse(m.Groups[1].Value, out var tagId) || tagId <= 0) continue; + var name = DecodeHtml(m.Groups[3].Value); + if (name.Length == 0 || list.Any(c => c.TagId == tagId)) continue; + list.Add(new CatalogCategory(4, tagId, m.Groups[2].Value.Trim(), name, false)); + } + return list; + } +} diff --git a/Mimante/src/BidooBidBot/Bidoo/DataResponseParser.cs b/Mimante/src/BidooBidBot/Bidoo/DataResponseParser.cs new file mode 100644 index 0000000..5d8d14b --- /dev/null +++ b/Mimante/src/BidooBidBot/Bidoo/DataResponseParser.cs @@ -0,0 +1,279 @@ +using System.Globalization; +using System.Text.RegularExpressions; + +namespace BidooBidBot.Bidoo; + +/// +/// Traduce le risposte di data.php e bid.php. Pura, senza stato: il formato è +/// posizionale e non documentato, quindi è il punto in cui un cambiamento del sito si vede +/// per primo, e i test con risposte registrate sono l'unico modo di accorgersene. +/// +/// Formato: serverTs*[core,storico]. core = +/// id;STATO;scadenza;prezzoCent;utente; nelle aste concluse porta in coda +/// |pagate|gratis|super|shock|manuali|automatiche|. La virgola separa core e +/// storico; il | separa i record dello storico (prezzoCent;utente;istante;tipo). +/// Tagliare sul primo | faceva sparire la puntata più recente (difetto corretto nel +/// legacy il 2026-08-01). +/// +public static partial class DataResponseParser +{ + public readonly struct ParseResult + { + public AuctionState? State { get; init; } + public string? Error { get; init; } + public bool Success => State != null; + + public static ParseResult Fail(string reason) => new() { Error = reason }; + public static ParseResult Ok(AuctionState state) => new() { State = state }; + } + + /// Interpreta una risposta di data.php per una sola asta. + /// Utente corrente, per riconoscere le proprie puntate. + /// Tetto alle puntate lette dallo storico (0 = tutte). + public static ParseResult Parse( + string auctionId, string? response, int latencyMs, long receivedTicks, string? username, + int maxHistoryEntries = 50, BidooReferences? refs = null) + { + refs ??= BidooReferences.Default; + var p = refs.Parsing; + + if (string.IsNullOrWhiteSpace(response)) return ParseResult.Fail("risposta vuota"); + + var starIndex = response.IndexOf('*'); + if (starIndex < 0) return ParseResult.Fail("separatore '*' assente"); + + // Prima di '*' possono esserci altri campi separati da '|': il timestamp è il primo. + var timestampPart = response[..starIndex]; + var pipeInTimestamp = timestampPart.IndexOf('|'); + var serverTimestamp = (pipeInTimestamp > 0 ? timestampPart[..pipeInTimestamp] : timestampPart).Trim(); + + var mainData = response[(starIndex + 1)..]; + var bracketStart = mainData.IndexOf('['); + var bracketEnd = mainData.LastIndexOf(']'); + if (bracketStart < 0 || bracketEnd < 0 || bracketEnd < bracketStart) + return ParseResult.Fail("parentesi quadre assenti o invertite"); + + var auctionData = mainData[(bracketStart + 1)..bracketEnd]; + + var comma = auctionData.IndexOf(p.CoreHistorySeparator, StringComparison.Ordinal); + var coreData = comma >= 0 ? auctionData[..comma] : auctionData; + var historyData = comma >= 0 ? auctionData[(comma + p.CoreHistorySeparator.Length)..] : ""; + + // Aste concluse: id;OFF;scadenza;prezzo;vincitore;tipo;durata;|pagate|gratis|... + var winnerDetails = ""; + var pipeInCore = coreData.IndexOf(p.HistorySeparator, StringComparison.Ordinal); + if (pipeInCore >= 0) + { + winnerDetails = coreData[(pipeInCore + p.HistorySeparator.Length)..]; + coreData = coreData[..pipeInCore]; + } + + var fields = coreData.Split(p.CoreSeparator); + if (fields.Length < 5) return ParseResult.Fail($"attesi almeno 5 campi, trovati {fields.Length}"); + + var state = new AuctionState + { + AuctionId = auctionId, + SnapshotTimeUtc = DateTime.UtcNow, + PollingLatencyMs = latencyMs, + ReceivedTicks = receivedTicks, + LastBidder = fields[4].Trim() + }; + + var apiStatus = fields[1].Trim().ToUpperInvariant(); + var hasWinner = state.LastBidder.Length > 0; + var iAmWinner = hasWinner && !string.IsNullOrEmpty(username) && + state.LastBidder.Equals(username, StringComparison.OrdinalIgnoreCase); + state.IsMyBid = iAmWinner; + + if (long.TryParse(serverTimestamp, NumberStyles.Integer, CultureInfo.InvariantCulture, out var serverTs) && + long.TryParse(fields[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out var expiryTs)) + { + state.Timer = Math.Max(0, expiryTs - serverTs); + state.ServerUnixSeconds = serverTs; + state.ExpiryUnixSeconds = expiryTs; + } + + if (int.TryParse(fields[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out var priceIndex)) + state.Price = priceIndex * 0.01; + + state.Status = DetermineStatus(apiStatus, hasWinner, iAmWinner, state.Timer, refs); + + if (winnerDetails.Length > 0) + { + var (paid, free) = ParseWinnerBids(winnerDetails); + state.WinnerBidsPaid = paid; + state.WinnerBidsFree = free; + } + + if (historyData.Length > 0) + state.RecentBidsHistory = ParseBidHistory(historyData, username, maxHistoryEntries, refs); + + return ParseResult.Ok(state); + } + + /// + /// Puntate spese dal vincitore: pagate|gratis|super|shock|manuali|automatiche|. + /// È l'unica fonte attendibile (lo storico si ferma alle ultime cinquanta). + /// + public static (int? Paid, int? Free) ParseWinnerBids(string? details) + { + if (string.IsNullOrWhiteSpace(details)) return (null, null); + + var parts = details.Split('|'); + if (parts.Length < 2) return (null, null); + + int? paid = int.TryParse(parts[0].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var pv) && pv >= 0 ? pv : null; + int? free = int.TryParse(parts[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var fv) && fv >= 0 ? fv : null; + return (paid, free); + } + + /// + /// La risposta di bid.php: ok|pagateResidue|gratisResidue|gratisUsateQui|pagateUsateQui|0|idAsta|0|0. + /// Il secondo campo NON è il saldo totale. Errori: error|messaggio o no|messaggio, + /// a volte con HTML; alive è un keep-alive, non una conferma. + /// + public static BidResponse ParseBidResponse(string? body) + { + var text = (body ?? "").Trim(); + if (text.Length == 0) return new BidResponse(false, null, null, null, null, "risposta vuota"); + + var parts = text.Split('|'); + var head = parts[0].Trim(); + + if (head.Equals("ok", StringComparison.OrdinalIgnoreCase)) + return new BidResponse(true, Field(parts, 1), Field(parts, 2), Field(parts, 3), Field(parts, 4), null); + + if (head.StartsWith("error", StringComparison.OrdinalIgnoreCase) || head.Equals("no", StringComparison.OrdinalIgnoreCase)) + { + var message = parts.Length > 1 ? string.Join(" ", parts.Skip(1)) : text; + message = HtmlTags().Replace(message, "\n"); + var firstLine = message.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) + .Select(l => l.Trim()).FirstOrDefault(l => l.Length > 0); + message = (firstLine ?? text).Trim(); + while (message.Contains(" ", StringComparison.Ordinal)) message = message.Replace(" ", " ", StringComparison.Ordinal); + return new BidResponse(false, null, null, null, null, message.Length == 0 ? text : message); + } + + if (text.Contains("alive", StringComparison.OrdinalIgnoreCase)) + return new BidResponse(false, null, null, null, null, "risposta keep-alive invece della conferma", KeepAlive: true); + + return new BidResponse(false, null, null, null, null, $"risposta non riconosciuta: {Truncate(text, 120)}"); + } + + /// ON = in corso, OFF = conclusa, STOP = sospesa (Bidoo ferma le aste di notte). + public static AuctionStatus DetermineStatus(string apiStatus, bool hasWinner, bool iAmWinner, double timerSeconds, BidooReferences? refs = null) + { + refs ??= BidooReferences.Default; + var p = refs.Parsing; + + if (apiStatus == p.StatusStop) return AuctionStatus.Paused; + if (apiStatus == p.StatusOff) + { + if (!hasWinner) return AuctionStatus.Closed; + return iAmWinner ? AuctionStatus.EndedWon : AuctionStatus.EndedLost; + } + if (apiStatus == p.StatusOn) + { + if (hasWinner) return AuctionStatus.Running; + return timerSeconds > refs.Timing.ScheduledIfTimerAboveS ? AuctionStatus.Scheduled : AuctionStatus.Pending; + } + return AuctionStatus.Unknown; + } + + /// Storico: prezzoCent;utente;istanteUnix;tipo separati da |; tipo 3 = automatica, 1 = manuale. + public static List? ParseBidHistory(string historyData, string? username, int maxEntries = 50, BidooReferences? refs = null) + { + refs ??= BidooReferences.Default; + var p = refs.Parsing; + if (string.IsNullOrWhiteSpace(historyData)) return null; + + var entries = new List(); + foreach (var record in historyData.Split(p.HistorySeparator)) + { + if (maxEntries > 0 && entries.Count >= maxEntries) break; + if (string.IsNullOrWhiteSpace(record)) continue; + + var parts = record.Split(p.CoreSeparator); + if (parts.Length < 4) continue; + if (!int.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var priceIndex)) continue; + if (!long.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out var timestamp)) continue; + + var user = parts[1].Trim(); + var code = parts[3].Trim(); + entries.Add(new BidHistoryEntry + { + Price = priceIndex * 0.01m, + Username = user, + Timestamp = timestamp, + BidType = code == p.BidTypeManual ? BidHistoryEntry.TypeManual + : code == p.BidTypeAuto ? BidHistoryEntry.TypeAuto + : BidHistoryEntry.TypeUnknown, + IsMyBid = !string.IsNullOrEmpty(username) && user.Equals(username, StringComparison.OrdinalIgnoreCase) + }); + } + + return entries.Count > 0 ? entries : null; + } + + /// + /// La risposta a più aste: serverTs*(id;STATO;scadenza;prezzoCent;utente#id2;…). + /// Le righe che non si leggono si saltano. + /// + public static List ParseList(string? response, BidooReferences? refs = null) + { + refs ??= BidooReferences.Default; + var p = refs.Parsing; + var list = new List(); + if (string.IsNullOrWhiteSpace(response)) return list; + + var star = response.IndexOf('*'); + if (star < 0) return list; + var head = response[..star]; + var pipe = head.IndexOf('|'); + if (pipe > 0) head = head[..pipe]; + if (!long.TryParse(head.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var serverSeconds)) return list; + + var data = response[(star + 1)..].Trim(); + if (data.StartsWith('(') && data.EndsWith(')')) data = data[1..^1]; + if (data.StartsWith('[') && data.EndsWith(']')) data = data[1..^1]; + + foreach (var entry in data.Split(p.ListSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + // Ogni voce può portare il proprio storico dopo la virgola: qui non serve. + var core = entry; + var comma = core.IndexOf(p.CoreHistorySeparator, StringComparison.Ordinal); + if (comma >= 0) core = core[..comma]; + + var fields = core.Split(p.CoreSeparator); + if (fields.Length < 4) continue; + if (!long.TryParse(fields[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out var expiry)) expiry = 0; + if (!int.TryParse(fields[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out var cents)) continue; + + list.Add(new ListEntry(fields[0].Trim(), fields[1].Trim().ToUpperInvariant(), expiry, cents, + fields.Length > 4 ? fields[4].Trim() : "", serverSeconds)); + } + return list; + } + + /// + /// La risposta è la pagina di login al posto dei dati? È il segno della sessione scaduta + /// (insieme al 403). Una risposta di dati comincia con un numero. + /// + public static bool LooksLikeLoginPage(string? body, BidooReferences? refs = null) + { + refs ??= BidooReferences.Default; + if (string.IsNullOrWhiteSpace(body)) return false; + var trimmed = body.TrimStart(); + if (trimmed.Length > 0 && char.IsDigit(trimmed[0])) return false; + return refs.Recognizers.LoginPageMarkers.Any(m => m.Length > 0 && body.Contains(m, StringComparison.OrdinalIgnoreCase)); + } + + private static int? Field(string[] parts, int index) => + parts.Length > index && int.TryParse(parts[index].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var v) && v >= 0 ? v : null; + + private static string Truncate(string s, int max) => s.Length <= max ? s : s[..max] + "..."; + + [GeneratedRegex("<[^>]+>")] + private static partial Regex HtmlTags(); +} diff --git a/Mimante/src/BidooBidBot/Bidoo/bidoo.default.json b/Mimante/src/BidooBidBot/Bidoo/bidoo.default.json index 0967ef4..58cb340 100644 --- a/Mimante/src/BidooBidBot/Bidoo/bidoo.default.json +++ b/Mimante/src/BidooBidBot/Bidoo/bidoo.default.json @@ -1 +1,117 @@ -{} +{ + // Riferimenti del sito di Bidoo: indirizzi, intestazioni, espressioni per leggere le pagine. + // Questi sono i valori di fabbrica incorporati nel programma. Il file vero sta in + // /config/riferimenti/bidoo.json: basta scrivere lì le sole voci da cambiare, il resto + // resta di fabbrica, e il bot lo rilegge da solo entro pochi secondi (niente riavvio). + "baseUrl": "https://it.bidoo.com", + + // Vuoto = lo User-Agent salvato con la sessione (quello del browser dell'accesso). + "userAgent": "", + // Usato solo senza sessione (catalogo pubblico, prime prove). + "defaultUserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36", + + "endpoints": { + "auctionData": "/data.php?ALL={id}&LISTID=0", + "bid": "/bid.php?AID={id}&sup=0&shock=0", + "bulkPrices": "/data.php?LISTID={ids}&chk={unixMs}", + "userInfo": "/buy_bids.php", + "creditsStatus": "/update_credits_status.php?submit=1", + "auctionsWon": "/check_auctions_won.php", + "catalogFirstPage": "/get_auctions.php?tab={tab}&tag={tag}", + "catalogNextPage": "/get_auction_updates.php", + "catalogNextPageBody": "prefetch=true&view={view}&tab={tab}&tag={tag}", + "catalogLegacy": "/index.php?selectBids=1&tab={tab}&tag={tag}", + "home": "/", + "auctionPage": "/auction.php?a={id}", + "auctionPageSlug": "/auction.php?a={slug}", + "login": "/login.php", + "warmUp": "/favicon.ico" + }, + + "headers": { + "ajaxAccept": "*/*", + "documentAccept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "xRequestedWith": "XMLHttpRequest", + "acceptLanguage": "it-IT,it;q=0.9,en;q=0.7" + }, + + "recognizers": { + "userId": "BidooCnf\\.userObj\\.id\\s*=\\s*'([^']+)'", + "username": "BidooCnf\\.userObj\\.username\\s*=\\s*'([^']+)'", + "remainingBids": [ + "]*id=\"divSaldoBidMobile\"[^>]*>(\\d+)", + "]*id=\"divSaldoBidBottom\"[^>]*>(\\d+)", + "]*id=\"divSaldoBid\"[^>]*>(\\d+)" + ], + "shopCredit": "]*class=\"cbstotal\"[^>]*>([\\d.]+)", + "creditsCount": "]*id=\"bids_count\"[^>]*>(\\d+)", + "loginPageMarkers": [ "login.php" ], + "sessionCookie": "__stattrb", + + "auctionTitle": "([^<]+)", + "auctionTitleSuffix": " - Bidoo", + "productValue": [ + "]*class=\"[^\"]*product-value[^\"]*\"[^>]*>.*?Valore:.*?]*>([0-9]+[,.]?[0-9]*)\\s*€", + "buyitnow-button[^>]*>.*?([0-9]+[,.]?[0-9]*)\\s*€", + "COMPRALO\\s+ORA\\s+A\\s+([0-9]+[,.]?[0-9]*)\\s*€" + ], + "shipping": [ + "Spese\\s+di\\s+spedizione:.*?]*>([0-9]+[,.]?[0-9]*)\\s*€", + "Spese\\s+di\\s+transazione:.*?]*>([0-9]+[,.]?[0-9]*)\\s*€" + ], + "winLimit": "Limiti\\s+di\\s+vincita:.*?]*>([^<]+)", + "productImage": "(https?://[^\"'\\s]+/products/[^\"'\\s]+\\.(?:jpg|jpeg|png|webp))", + "productId": "data-id-product=\"(\\d+)\"", + + "catalogCard": "]+id=\"divAsta(\\d+)\"", + "catalogDataUrl": "data-url=\"([^\"]+)\"", + "catalogDataFreq": "data-freq=\"(\\d+)\"", + "catalogDataCredit": "data-credit=\"(\\d+)\"", + "catalogDataCreditValue": "data-credit-value=\"(\\d+)\"", + "catalogDataProduct": "data-id-product=\"(\\d+)\"", + "catalogImage": "]+src=\"(https?://[^\"]+/products/[^\"]+)\"", + "catalogName": "]+class=\"name[^\"]*\"[^>]*>([^<]+)", + "catalogBuyNow": "buy-rapid-now[^>]*>[\\s\\S]{0,400}?([0-9]{1,3}(?:\\.[0-9]{3})+(?:,[0-9]{1,2})?|[0-9]+(?:[,.][0-9]{1,2})?)\\s*(?:€|€|€)", + "catalogManualOnlyMarker": "bi-noauto", + "catalogCategory": "javascript:selectBids\\(4,\\s*true,\\s*false,\\s*(\\d+)\\);\\s*\"\\s+data-tab=\"4\"\\s+data-slug=\"([^\"]*)\"\\s+data-tag=\"\\d+\">]*>([^<]+)", + + "auctionIdInPath": [ "/asta/[^/]*-(\\d{6,})", "/asta/(\\d{6,})" ], + "auctionIdInQuery": "[?&]a=([^&#]+)", + "auctionIdDigits": "(\\d{6,})$" + }, + + "timing": { + // I controlli di strategia partono questo tanto prima dell'istante di fuoco. + "preCheckMs": 60, + // Sotto questi secondi sul cronometro, in Attiva, il polling passa alla cadenza critica. + "criticalWindowS": 4, + // Un'asta ON senza vincitore con il cronometro oltre questa soglia è programmata. + "scheduledIfTimerAboveS": 1800 + }, + + "limits": { + "maxConcurrency": 24, + "bidLaneConnections": 3, + "bidLaneKeepAliveSeconds": 20, + "bidTimeoutMs": 3000, + "requestTimeoutMs": 8000, + "brakeMinMs": 1000, + "brakeMaxMs": 8000, + "historyMaxEntries": 50, + "bulkPricesChunk": 60, + "catalogPageSize": 50, + "catalogMaxPages": 200 + }, + + "parsing": { + "coreSeparator": ";", + "historySeparator": "|", + "coreHistorySeparator": ",", + "listSeparator": "#", + "bidTypeManual": "1", + "bidTypeAuto": "3", + "statusOn": "ON", + "statusOff": "OFF", + "statusStop": "STOP" + } +} diff --git a/Mimante/src/BidooBidBot/Net/BidLane.cs b/Mimante/src/BidooBidBot/Net/BidLane.cs new file mode 100644 index 0000000..8dc133f --- /dev/null +++ b/Mimante/src/BidooBidBot/Net/BidLane.cs @@ -0,0 +1,85 @@ +using System.Net; +using BidooBidBot.Bidoo; + +namespace BidooBidBot.Net; + +/// +/// La corsia dedicata alle puntate (specifica §6.4): un handler tutto suo con poche +/// connessioni (3) tenute calde da una richiesta leggera ogni 20 s, nessun limitatore, +/// nessuna coda, tempo massimo 3 s. Così una puntata parte sempre su una connessione già +/// aperta e non aspetta mai dietro al polling di altre aste. +/// +/// Se la corsia fallisce per un errore di rete, chi chiama può ritentare una sola +/// volta sul pool normale nello stesso ciclo, se c'è ancora tempo. +/// +public sealed class BidLane : IDisposable +{ + private readonly BidooTransport _transport; + private readonly Func _refs; + private readonly HttpClient _client; + private readonly Timer? _keepAlive; + private long _bids; + private long _failures; + + public BidLane(BidooTransport transport, Func refs, HttpMessageHandler? handler = null, bool keepWarm = true) + { + _transport = transport; + _refs = refs; + var limits = refs().Limits; + + var h = handler ?? BidooTransport.CreateHandler(Math.Max(1, limits.BidLaneConnections)); + _client = new HttpClient(h, disposeHandler: handler == null) + { + Timeout = TimeSpan.FromMilliseconds(Math.Max(500, limits.BidTimeoutMs)), + DefaultRequestVersion = HttpVersion.Version20, + DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower + }; + + if (keepWarm) + { + var period = TimeSpan.FromSeconds(Math.Max(5, limits.BidLaneKeepAliveSeconds)); + _keepAlive = new Timer(_ => _ = WarmAsync(), null, TimeSpan.FromSeconds(1), period); + } + } + + public long Bids => Interlocked.Read(ref _bids); + public long Failures => Interlocked.Read(ref _failures); + + /// Latenze delle puntate (andata e ritorno di bid.php). + public LatencyStats BidLatency { get; } = new(300); + + /// + /// Invia la puntata sulla corsia. La richiesta ha le stesse intestazioni del trasporto + /// (cookie, User-Agent), più Origin e Referer alla pagina dell'asta. + /// + public async Task SendBidAsync(string url, string referer, CancellationToken ct) + { + var request = _transport.BuildGet(url, referer); + request.Headers.TryAddWithoutValidation("Origin", _refs().BaseUrl); + + Interlocked.Increment(ref _bids); + var outcome = await _transport.ExecuteAsync(_client, request, ct).ConfigureAwait(false); + if (outcome.IsNetworkError) Interlocked.Increment(ref _failures); + else BidLatency.Add(outcome.LatencyMs); + return outcome; + } + + /// Tiene aperte le connessioni della corsia con una richiesta leggera. + public async Task WarmAsync() + { + try + { + var refs = _refs(); + var tasks = Enumerable.Range(0, Math.Max(1, refs.Limits.BidLaneConnections)).Select(_ => + _transport.ExecuteAsync(_client, _transport.BuildGet(refs.Url(refs.Endpoints.WarmUp), ajax: false), CancellationToken.None)); + await Task.WhenAll(tasks).ConfigureAwait(false); + } + catch { /* riscaldamento facoltativo */ } + } + + public void Dispose() + { + _keepAlive?.Dispose(); + _client.Dispose(); + } +} diff --git a/Mimante/src/BidooBidBot/Net/BidooTransport.cs b/Mimante/src/BidooBidBot/Net/BidooTransport.cs new file mode 100644 index 0000000..03890ae --- /dev/null +++ b/Mimante/src/BidooBidBot/Net/BidooTransport.cs @@ -0,0 +1,332 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Security; +using System.Text; +using BidooBidBot.Bidoo; + +namespace BidooBidBot.Net; + +/// +/// Trasporto HTTP verso Bidoo, dimensionato per un flusso continuo di richieste +/// (specifica §6.4, portato da Net/BidooHttpClient del legacy). +/// +/// +/// Un solo con pool ampio e connessioni calde, +/// HTTP/2 con ripiego, decompressione automatica, cookie a mano. +/// User-Agent: lo stesso del browser dell'accesso assistito, salvato con la sessione. +/// Token bucket (40 richieste/s di fabbrica) con riserva per il polling, semaforo di +/// concorrenza; le richieste saltano entrambi. +/// Freno del server: su 429/503 si aspetta 1 s, poi il doppio fino a 8 s; si +/// rilascia alla prima risposta buona. Le puntate non passano dal freno. +/// +/// +public sealed class BidooTransport : IDisposable +{ + private readonly Func _refs; + private readonly HttpMessageHandler _handler; + private readonly HttpClient _client; + private readonly SemaphoreSlim _concurrency; + private readonly TokenBucket _limiter; + + private volatile string _cookie = ""; + private volatile string _sessionUserAgent = ""; + + private long _sent; + private long _failed; + private long _brakes; + + private long _brakeUntil; + private int _brakeMs; + + public BidooTransport(Func refs, double requestsPerSecond, HttpMessageHandler? handler = null) + { + _refs = refs; + var limits = refs().Limits; + _brakeMs = limits.BrakeMinMs; + + _handler = handler ?? CreateHandler(64); + _client = new HttpClient(_handler, disposeHandler: handler == null) + { + Timeout = TimeSpan.FromMilliseconds(Math.Max(1000, limits.RequestTimeoutMs)), + DefaultRequestVersion = HttpVersion.Version20, + DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower + }; + _client.DefaultRequestHeaders.ConnectionClose = false; + + _concurrency = new SemaphoreSlim(Math.Max(1, limits.MaxConcurrency), Math.Max(1, limits.MaxConcurrency)); + _limiter = new TokenBucket(requestsPerSecond); + } + + /// Un handler come serve a Bidoo: pool caldo, HTTP/2, cookie gestiti a mano. + public static SocketsHttpHandler CreateHandler(int maxConnections) => new() + { + UseCookies = false, + UseProxy = false, + AutomaticDecompression = DecompressionMethods.All, + // Bidoo risponde 302 su diverse pagine: i redirect sono sulla stessa origine e + // l'intestazione Cookie scritta a mano resta. + AllowAutoRedirect = true, + MaxAutomaticRedirections = 5, + MaxConnectionsPerServer = maxConnections, + PooledConnectionLifetime = TimeSpan.FromMinutes(10), + PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2), + ConnectTimeout = TimeSpan.FromSeconds(5), + EnableMultipleHttp2Connections = true, + ResponseDrainTimeout = TimeSpan.FromSeconds(2), + SslOptions = new SslClientAuthenticationOptions + { + ApplicationProtocols = new List { SslApplicationProtocol.Http2, SslApplicationProtocol.Http11 } + } + }; + + public long RequestsSent => Interlocked.Read(ref _sent); + public long RequestsFailed => Interlocked.Read(ref _failed); + public long Brakes => Interlocked.Read(ref _brakes); + + /// Latenze delle richieste di polling andate a buon fine. + public LatencyStats PollLatency { get; } = new(300); + + public string Cookie => _cookie; + public bool HasCookie => _cookie.Length > 0; + public string UserAgent => _refs().EffectiveUserAgent(_sessionUserAgent); + + /// Scatta quando il server ha rinnovato un cookie della sessione (Set-Cookie). + public event Action? CookieChanged; + + public void SetSession(string? cookie, string? userAgent) + { + _cookie = cookie?.Trim() ?? ""; + _sessionUserAgent = userAgent?.Trim() ?? ""; + } + + /// Limiti di ritmo a caldo, senza ricreare il trasporto. + public void Configure(double requestsPerSecond) => _limiter.SetRate(requestsPerSecond); + + /// Millisecondi di freno ancora da scontare. Zero quando si va liberi. + public int BrakeRemainingMs + { + get + { + var left = (Interlocked.Read(ref _brakeUntil) - Stopwatch.GetTimestamp()) * 1000 / Stopwatch.Frequency; + return left > 0 ? (int)left : 0; + } + } + + private void Brake() + { + var limits = _refs().Limits; + var duration = Volatile.Read(ref _brakeMs); + Interlocked.Exchange(ref _brakeUntil, Stopwatch.GetTimestamp() + duration * Stopwatch.Frequency / 1000); + Volatile.Write(ref _brakeMs, Math.Min(limits.BrakeMaxMs, duration * 2)); + Interlocked.Increment(ref _brakes); + } + + private void ReleaseBrake() => Volatile.Write(ref _brakeMs, _refs().Limits.BrakeMinMs); + + /// Una GET completa di cookie, User-Agent e intestazioni di contesto. + public HttpRequestMessage BuildGet(string url, string? referer = null, bool ajax = true) + { + var refs = _refs(); + var request = new HttpRequestMessage(HttpMethod.Get, url); + AddCommonHeaders(request, refs, referer); + + var h = request.Headers; + if (ajax) + { + h.TryAddWithoutValidation("Accept", refs.Headers.AjaxAccept); + h.TryAddWithoutValidation("X-Requested-With", refs.Headers.XRequestedWith); + h.TryAddWithoutValidation("Sec-Fetch-Dest", "empty"); + h.TryAddWithoutValidation("Sec-Fetch-Mode", "cors"); + h.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin"); + } + else + { + h.TryAddWithoutValidation("Accept", refs.Headers.DocumentAccept); + h.TryAddWithoutValidation("Sec-Fetch-Dest", "document"); + h.TryAddWithoutValidation("Sec-Fetch-Mode", "navigate"); + h.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin"); + } + return request; + } + + /// Una POST con corpo già codificato (application/x-www-form-urlencoded). + public HttpRequestMessage BuildPost(string url, string formBody, string? referer = null) + { + var refs = _refs(); + var request = new HttpRequestMessage(HttpMethod.Post, url) + { + Content = new StringContent(formBody, Encoding.UTF8, "application/x-www-form-urlencoded") + }; + AddCommonHeaders(request, refs, referer); + var h = request.Headers; + h.TryAddWithoutValidation("Accept", refs.Headers.AjaxAccept); + h.TryAddWithoutValidation("X-Requested-With", refs.Headers.XRequestedWith); + h.TryAddWithoutValidation("Origin", refs.BaseUrl); + h.TryAddWithoutValidation("Sec-Fetch-Dest", "empty"); + h.TryAddWithoutValidation("Sec-Fetch-Mode", "cors"); + h.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin"); + return request; + } + + private void AddCommonHeaders(HttpRequestMessage request, BidooReferences refs, string? referer) + { + var h = request.Headers; + h.TryAddWithoutValidation("User-Agent", refs.EffectiveUserAgent(_sessionUserAgent)); + h.TryAddWithoutValidation("Accept-Language", refs.Headers.AcceptLanguage); + var cookie = _cookie; + if (cookie.Length > 0) h.TryAddWithoutValidation("Cookie", cookie); + h.TryAddWithoutValidation("Referer", referer ?? refs.BaseUrl.TrimEnd('/') + "/"); + } + + /// Invia rispettando ritmo, freno e concorrenza (salvo le Critical). + public async Task SendAsync(HttpRequestMessage request, RequestPriority priority, CancellationToken ct) + { + var critical = priority == RequestPriority.Critical; + + if (!critical) + { + var brake = BrakeRemainingMs; + if (brake > 0) await Task.Delay(brake, ct).ConfigureAwait(false); + await _limiter.WaitAsync(priority == RequestPriority.Background, ct).ConfigureAwait(false); + await _concurrency.WaitAsync(ct).ConfigureAwait(false); + } + + try + { + var outcome = await ExecuteAsync(_client, request, ct).ConfigureAwait(false); + Interlocked.Increment(ref _sent); + if (!outcome.Success) Interlocked.Increment(ref _failed); + + if (outcome.StatusCode is 429 or 503) Brake(); + else if (outcome.Success) ReleaseBrake(); + + if (outcome.Success && priority == RequestPriority.Normal) PollLatency.Add(outcome.LatencyMs); + return outcome; + } + finally + { + if (!critical) _concurrency.Release(); + } + } + + /// + /// La richiesta vera e propria: corpo, stato, latenza misurata con Stopwatch, cookie + /// rinnovati dal server. Usata anche dalla corsia delle puntate. + /// + public async Task ExecuteAsync(HttpClient client, HttpRequestMessage request, CancellationToken ct) + { + var start = Stopwatch.GetTimestamp(); + try + { + using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + var body = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + var received = Stopwatch.GetTimestamp(); + + if (response.Headers.TryGetValues("Set-Cookie", out var setCookies)) MergeCookies(setCookies); + + return new HttpOutcome + { + Success = response.IsSuccessStatusCode, + StatusCode = (int)response.StatusCode, + Body = body, + LatencyMs = (int)((received - start) * 1000 / Stopwatch.Frequency), + SentTicks = start, + ReceivedTicks = received + }; + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + return HttpOutcome.Failure(ex is TaskCanceledException ? "nessuna risposta nel tempo massimo" : ex.Message, start); + } + finally + { + request.Dispose(); + } + } + + /// + /// Il server rinnova un cookie: lo si aggiorna nella stringa della sessione, come farebbe + /// il browser. I cookie cancellati (valore vuoto o scaduti) si tolgono. + /// + private void MergeCookies(IEnumerable setCookies) + { + var current = _cookie; + if (current.Length == 0) return; + + var merged = CookieText.Merge(current, setCookies); + if (merged == current) return; + _cookie = merged; + try { CookieChanged?.Invoke(merged); } catch { /* chi salva non deve fermare la richiesta */ } + } + + /// Apre in anticipo qualche connessione, così le prime richieste non pagano TCP+TLS. + public async Task WarmUpAsync(CancellationToken ct = default) + { + var refs = _refs(); + var tasks = Enumerable.Range(0, 4) + .Select(_ => SendAsync(BuildGet(refs.Url(refs.Endpoints.WarmUp), ajax: false), RequestPriority.Background, ct)) + .ToArray(); + try { await Task.WhenAll(tasks).ConfigureAwait(false); } + catch { /* il riscaldamento è facoltativo */ } + } + + public void Dispose() + { + _client.Dispose(); + _concurrency.Dispose(); + } +} + +/// Operazioni sulla stringa dei cookie («a=1; b=2»). Pura, sotto test. +public static class CookieText +{ + public static List<(string Name, string Value)> Split(string? cookie) + { + var list = new List<(string, string)>(); + foreach (var part in (cookie ?? "").Split(';')) + { + var p = part.Trim(); + var eq = p.IndexOf('='); + if (eq <= 0) continue; + list.Add((p[..eq].Trim(), p[(eq + 1)..].Trim())); + } + return list; + } + + public static string Join(IEnumerable<(string Name, string Value)> cookies) => + string.Join("; ", cookies.Select(c => $"{c.Name}={c.Value}")); + + public static bool Contains(string? cookie, string name) => + Split(cookie).Any(c => c.Name.Equals(name, StringComparison.Ordinal) && c.Value.Length > 0); + + /// Applica le intestazioni Set-Cookie di una risposta alla stringa corrente. + public static string Merge(string current, IEnumerable setCookies) + { + var jar = Split(current); + foreach (var header in setCookies) + { + var first = header.Split(';')[0].Trim(); + var eq = first.IndexOf('='); + if (eq <= 0) continue; + var name = first[..eq].Trim(); + var value = first[(eq + 1)..].Trim(); + + var expired = value.Length == 0 || value.Equals("deleted", StringComparison.OrdinalIgnoreCase) || + header.Contains("Max-Age=0", StringComparison.OrdinalIgnoreCase) || + header.Contains("expires=Thu, 01 Jan 1970", StringComparison.OrdinalIgnoreCase); + + var index = jar.FindIndex(c => c.Name.Equals(name, StringComparison.Ordinal)); + if (expired) + { + if (index >= 0) jar.RemoveAt(index); + } + else if (index >= 0) jar[index] = (name, value); + else jar.Add((name, value)); + } + return Join(jar); + } +} diff --git a/Mimante/src/BidooBidBot/Net/HttpOutcome.cs b/Mimante/src/BidooBidBot/Net/HttpOutcome.cs new file mode 100644 index 0000000..dfed6a0 --- /dev/null +++ b/Mimante/src/BidooBidBot/Net/HttpOutcome.cs @@ -0,0 +1,109 @@ +using System.Diagnostics; + +namespace BidooBidBot.Net; + +/// Priorità di una richiesta. Le puntate non si accodano mai dietro al polling. +public enum RequestPriority +{ + /// Catalogo, dati del conto, recuperi storici: cedono il passo, lasciano una riserva di gettoni. + Background = 0, + + /// Polling delle aste. + Normal, + + /// Salta limitatore, freno e coda. Riservato alle puntate. + Critical +} + +/// Esito di una richiesta HTTP: corpo, stato, latenza, istante di ricezione. +public sealed class HttpOutcome +{ + public bool Success { get; init; } + public int StatusCode { get; init; } + public string Body { get; init; } = ""; + public string? Error { get; init; } + public int LatencyMs { get; init; } + + /// Tick di Stopwatch all'arrivo della risposta (monotono). + public long ReceivedTicks { get; init; } + + /// Tick di Stopwatch alla partenza: con dà il giro completo. + public long SentTicks { get; init; } + + public bool IsNetworkError => StatusCode == 0; + + public string Describe() => Error ?? $"HTTP {StatusCode}"; + + public static HttpOutcome Failure(string error, long sent) => new() + { + Success = false, + StatusCode = 0, + Error = error, + SentTicks = sent, + ReceivedTicks = Stopwatch.GetTimestamp(), + LatencyMs = (int)((Stopwatch.GetTimestamp() - sent) * 1000 / Stopwatch.Frequency) + }; +} + +/// +/// Latenze recenti in una finestra circolare, con i percentili a richiesta. Vive in memoria: +/// nel database finiscono solo le aggregazioni per asta e per puntata. +/// +public sealed class LatencyStats +{ + private readonly int[] _window; + private readonly object _sync = new(); + private int _index; + private int _count; + + public LatencyStats(int size = 300) => _window = new int[Math.Max(10, size)]; + + public int Count { get { lock (_sync) return _count; } } + + public void Add(int ms) + { + if (ms <= 0 || ms > 30_000) return; + lock (_sync) + { + _window[_index] = ms; + _index = (_index + 1) % _window.Length; + if (_count < _window.Length) _count++; + } + } + + /// Il percentile richiesto (0-1); null senza campioni. + public int? Percentile(double p) + { + int[] copy; + lock (_sync) + { + if (_count == 0) return null; + copy = new int[_count]; + Array.Copy(_window, copy, _count); + } + Array.Sort(copy); + var i = (int)Math.Ceiling(p * copy.Length) - 1; + return copy[Math.Clamp(i, 0, copy.Length - 1)]; + } + + public double? Average() + { + lock (_sync) + { + if (_count == 0) return null; + long sum = 0; + for (var i = 0; i < _count; i++) sum += _window[i]; + return (double)sum / _count; + } + } + + public int[] Snapshot() + { + lock (_sync) + { + var copy = new int[_count]; + Array.Copy(_window, copy, _count); + return copy; + } + } +} diff --git a/Mimante/src/BidooBidBot/Net/TokenBucket.cs b/Mimante/src/BidooBidBot/Net/TokenBucket.cs new file mode 100644 index 0000000..d176caf --- /dev/null +++ b/Mimante/src/BidooBidBot/Net/TokenBucket.cs @@ -0,0 +1,76 @@ +using System.Diagnostics; + +namespace BidooBidBot.Net; + +/// +/// Token bucket a rilascio continuo: un gettone per richiesta, e si aspetta solo il tempo +/// di rigenerarlo. Nessun timer, nessun thread. +/// +/// Le richieste di fondo (catalogo, conto) lasciano una riserva di gettoni alle +/// interrogazioni delle aste: nel legacy un tetto di 40 al secondo spartito alla pari fra +/// tutto faceva interrogare ogni ~600 ms le aste negli ultimi secondi, dove il ritardo costa +/// l'asta. Zero o meno = nessun limite. +/// +public sealed class TokenBucket +{ + private readonly object _sync = new(); + private double _capacity; + private double _rate; + private double _tokens; + private long _lastTicks; + + /// Quota di capacità che le richieste di fondo non possono toccare. + public double BackgroundReserve { get; set; } = 0.25; + + public TokenBucket(double ratePerSecond) + { + SetRate(ratePerSecond); + _tokens = _capacity; + _lastTicks = Stopwatch.GetTimestamp(); + } + + public double Rate { get { lock (_sync) return _rate; } } + + public void SetRate(double ratePerSecond) + { + lock (_sync) + { + _rate = ratePerSecond; + _capacity = Math.Max(8, Math.Abs(ratePerSecond)); + if (_tokens > _capacity) _tokens = _capacity; + } + } + + /// Millisecondi da aspettare prima di poter partire (e prenota il gettone). + public double Reserve(bool background) + { + lock (_sync) + { + if (_rate <= 0) return 0; + + var now = Stopwatch.GetTimestamp(); + var elapsed = (now - _lastTicks) / (double)Stopwatch.Frequency; + _lastTicks = now; + _tokens = Math.Min(_capacity, _tokens + elapsed * _rate); + + var floor = background ? _capacity * BackgroundReserve : 0; + var needed = 1 + floor; + + if (_tokens >= needed) + { + _tokens -= 1; + return 0; + } + + var waitMs = (needed - _tokens) / _rate * 1000.0; + _tokens -= 1; // la richiesta è già in coda: il gettone è suo + return waitMs; + } + } + + public ValueTask WaitAsync(bool background, CancellationToken ct) + { + var ms = Reserve(background); + return ms <= 0 ? ValueTask.CompletedTask : new ValueTask(Task.Delay(TimeSpan.FromMilliseconds(Math.Min(ms, 5000)), ct)); + } +} diff --git a/Mimante/src/BidooBidBot/Program.cs b/Mimante/src/BidooBidBot/Program.cs index 36088a0..9037583 100644 --- a/Mimante/src/BidooBidBot/Program.cs +++ b/Mimante/src/BidooBidBot/Program.cs @@ -53,9 +53,10 @@ log.Info("AVVIO", $"{AppInfo.Name} {AppInfo.Version}, .NET {Environment.Version} await using var host = new BotHost(env, paths, log, fileLog); var app = WebServer.Build(host); +// SIGTERM (docker stop) e Ctrl+C arrivano al ciclo di vita del server web: da lì si ferma +// anche il bot, e il processo esce solo dopo lo spegnimento ordinato qui sotto. using var shutdown = new CancellationTokenSource(); -Console.CancelKeyPress += (_, e) => { e.Cancel = true; shutdown.Cancel(); }; -AppDomain.CurrentDomain.ProcessExit += (_, _) => { try { shutdown.Cancel(); } catch (ObjectDisposedException) { } }; +app.Lifetime.ApplicationStopping.Register(() => { try { shutdown.Cancel(); } catch (ObjectDisposedException) { } }); await app.StartAsync(shutdown.Token); log.Info("AVVIO", $"Interfaccia in ascolto su http://0.0.0.0:{env.HttpPort}"); diff --git a/Mimante/tests/BidooBidBot.Tests/Fixtures/bid-errore.txt b/Mimante/tests/BidooBidBot.Tests/Fixtures/bid-errore.txt new file mode 100644 index 0000000..ed1af69 --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/Fixtures/bid-errore.txt @@ -0,0 +1 @@ +error|Timer scaduto
Riprova \ No newline at end of file diff --git a/Mimante/tests/BidooBidBot.Tests/Fixtures/bid-ok.txt b/Mimante/tests/BidooBidBot.Tests/Fixtures/bid-ok.txt new file mode 100644 index 0000000..8478e68 --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/Fixtures/bid-ok.txt @@ -0,0 +1 @@ +ok|927|480|3|5|0|1234567|0|0 \ No newline at end of file diff --git a/Mimante/tests/BidooBidBot.Tests/Fixtures/data-conclusa.txt b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-conclusa.txt new file mode 100644 index 0000000..086b336 --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-conclusa.txt @@ -0,0 +1 @@ +1785597295*[95235087;OFF;1784757333;838;redberri;1;1h 24m;|0|25|0|0|0|0|,838;redberri;1784757325;1|837;semoricci;1784757318;3|836;redberri;1784757312;1] \ No newline at end of file diff --git a/Mimante/tests/BidooBidBot.Tests/Fixtures/data-in-corso.txt b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-in-corso.txt new file mode 100644 index 0000000..e0f6ffb --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-in-corso.txt @@ -0,0 +1 @@ +1785597356*[95755813;ON;1785597364;4;kikisi9;1,4;kikisi9;1785597356;1|3;casmeride;1785597348;1|2;kikisi9;1785597340;1] \ No newline at end of file diff --git a/Mimante/tests/BidooBidBot.Tests/Fixtures/data-lista.txt b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-lista.txt new file mode 100644 index 0000000..7674d5b --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-lista.txt @@ -0,0 +1 @@ +1764068200*(95216992;ON;1764068210;342;fedekikka2323#95216993;OFF;1764068100;120;tizio#95216994;ON;1764075000;1;) \ No newline at end of file diff --git a/Mimante/tests/BidooBidBot.Tests/Fixtures/data-vergine.txt b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-vergine.txt new file mode 100644 index 0000000..73d00d2 --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-vergine.txt @@ -0,0 +1 @@ +1785597337*[95760550;ON;1785597351;1;;,] \ No newline at end of file diff --git a/Mimante/tests/BidooBidBot.Tests/ProtocolTests.cs b/Mimante/tests/BidooBidBot.Tests/ProtocolTests.cs new file mode 100644 index 0000000..e671062 --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/ProtocolTests.cs @@ -0,0 +1,557 @@ +using System.Diagnostics; +using BidooBidBot.Bidoo; +using BidooBidBot.Net; +using Xunit; + +namespace BidooBidBot.Tests; + +internal static class Fixture +{ + public static string Read(string name) => + File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", name)); +} + +/// +/// data.php è posizionale e non documentato: se cambia forma l'unico sintomo è uno stato +/// sbagliato. Questi test fissano il contratto osservato sul campo (portati dal legacy). +/// +public class DataResponseParserTests +{ + private const string Sample = + "1764068200*[95216992;ON;1764068210;342;fedekikka2323;1," + + "342;fedekikka2323;1764068204;3|341;chamorro1984;1764068194;1]"; + + [Fact] + public void Legge_i_campi_principali() + { + var r = DataResponseParser.Parse("95216992", Sample, 50, 1000, "tizio"); + Assert.True(r.Success); + var s = r.State!; + Assert.Equal("95216992", s.AuctionId); + Assert.Equal(3.42, s.Price, 3); + Assert.Equal("fedekikka2323", s.LastBidder); + Assert.Equal(AuctionStatus.Running, s.Status); + Assert.False(s.IsMyBid); + } + + [Fact] + public void Espone_gli_istanti_assoluti_del_server() + { + var r = DataResponseParser.Parse("1", Sample, 50, 1000, null); + Assert.Equal(1764068200, r.State!.ServerUnixSeconds); + Assert.Equal(1764068210, r.State.ExpiryUnixSeconds); + Assert.Equal(10, r.State.Timer, 3); + } + + [Fact] + public void Riconosce_le_puntate_dell_utente_senza_badare_alle_maiuscole() + { + var r = DataResponseParser.Parse("1", Sample, 50, 1000, "FEDEKIKKA2323"); + Assert.True(r.State!.IsMyBid); + } + + [Fact] + public void Legge_lo_storico_con_tipo_e_prezzo() + { + var history = DataResponseParser.Parse("1", Sample, 50, 1000, "chamorro1984").State!.RecentBidsHistory!; + Assert.Equal(2, history.Count); + Assert.Equal(3.42m, history[0].Price); + Assert.Equal(BidHistoryEntry.TypeAuto, history[0].BidType); + Assert.False(history[0].IsMyBid); + Assert.Equal(BidHistoryEntry.TypeManual, history[1].BidType); + Assert.True(history[1].IsMyBid); + } + + [Fact] + public void Rispetta_il_tetto_sullo_storico() + { + var r = DataResponseParser.Parse("1", Sample, 50, 1000, null, maxHistoryEntries: 1); + Assert.Single(r.State!.RecentBidsHistory!); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("senza-asterisco")] + [InlineData("1764068200*nessuna-parentesi")] + [InlineData("1764068200*[troppo;pochi;campi]")] + public void Rifiuta_le_risposte_malformate_senza_eccezioni(string bad) + { + var r = DataResponseParser.Parse("1", bad, 50, 1000, null); + Assert.False(r.Success); + Assert.False(string.IsNullOrEmpty(r.Error)); + } + + [Fact] + public void Ignora_i_campi_extra_prima_dell_asterisco() + { + var r = DataResponseParser.Parse("1", "1764068200|altro|ancora*[1;ON;1764068210;342;tizio]", 50, 1000, null); + Assert.True(r.Success); + Assert.Equal(1764068200, r.State!.ServerUnixSeconds); + Assert.Null(r.State.RecentBidsHistory); + } + + [Theory] + [InlineData("ON", true, false, 10, AuctionStatus.Running)] + [InlineData("ON", true, true, 10, AuctionStatus.Running)] + [InlineData("ON", false, false, 10, AuctionStatus.Pending)] + [InlineData("ON", false, false, 3600, AuctionStatus.Scheduled)] + [InlineData("OFF", true, true, 0, AuctionStatus.EndedWon)] + [InlineData("OFF", true, false, 0, AuctionStatus.EndedLost)] + [InlineData("OFF", false, false, 0, AuctionStatus.Closed)] + [InlineData("STOP", true, false, 0, AuctionStatus.Paused)] + [InlineData("BOH", false, false, 0, AuctionStatus.Unknown)] + public void Traduce_lo_stato_del_server(string api, bool hasWinner, bool iAmWinner, double timer, AuctionStatus expected) + { + Assert.Equal(expected, DataResponseParser.DetermineStatus(api, hasWinner, iAmWinner, timer)); + } + + [Fact] + public void Una_vittoria_richiede_che_il_vincitore_sia_l_utente() + { + Assert.Equal(AuctionStatus.EndedWon, DataResponseParser.Parse("1", "100*[1;OFF;100;500;ioStesso]", 10, 0, "ioStesso").State!.Status); + Assert.Equal(AuctionStatus.EndedLost, DataResponseParser.Parse("1", "100*[1;OFF;100;500;unAltro]", 10, 0, "ioStesso").State!.Status); + } + + // ── Risposte vere registrate dal server (Fixtures) ────────────────── + + [Fact] + public void Asta_conclusa_con_le_puntate_del_vincitore() + { + var r = DataResponseParser.Parse("95235087", Fixture.Read("data-conclusa.txt"), 50, 0, null); + Assert.True(r.Success); + Assert.Equal("redberri", r.State!.LastBidder); + Assert.Equal(8.38, r.State.Price, 2); + Assert.Equal(AuctionStatus.EndedLost, r.State.Status); + Assert.Equal(0, r.State.WinnerBidsPaid); + Assert.Equal(25, r.State.WinnerBidsFree); + Assert.Equal(25, r.State.WinnerBidsTotal); + } + + [Fact] + public void La_puntata_piu_recente_non_si_perde() + { + var r = DataResponseParser.Parse("95755813", Fixture.Read("data-in-corso.txt"), 50, 0, null); + var history = r.State!.RecentBidsHistory!; + Assert.Equal(3, history.Count); + Assert.Equal("kikisi9", history[0].Username); + Assert.Equal(0.04m, history[0].Price); + Assert.Null(r.State.WinnerBidsTotal); + Assert.Equal(AuctionStatus.Running, r.State.Status); + } + + [Fact] + public void Unasta_senza_puntate_si_legge_lo_stesso() + { + var r = DataResponseParser.Parse("95760550", Fixture.Read("data-vergine.txt"), 50, 0, null); + Assert.True(r.Success); + Assert.Equal("", r.State!.LastBidder); + Assert.Null(r.State.RecentBidsHistory); + Assert.Equal(AuctionStatus.Pending, r.State.Status); + } + + [Theory] + [InlineData("0|25|0|0|0|0|", 0, 25)] + [InlineData("371|0|0|0|0|0|", 371, 0)] + [InlineData("12|3", 12, 3)] + public void Legge_pagate_e_gratis(string tail, int paid, int free) + { + var (p, f) = DataResponseParser.ParseWinnerBids(tail); + Assert.Equal(paid, p); + Assert.Equal(free, f); + } + + [Theory] + [InlineData("")] + [InlineData("42")] + [InlineData("x|y")] + public void Una_coda_incomprensibile_non_inventa_numeri(string tail) + { + var (p, f) = DataResponseParser.ParseWinnerBids(tail); + Assert.True(p is null || f is null); + } + + [Fact] + public void La_risposta_a_piu_aste_si_legge_riga_per_riga() + { + var list = DataResponseParser.ParseList(Fixture.Read("data-lista.txt")); + Assert.Equal(3, list.Count); + Assert.Equal("95216992", list[0].AuctionId); + Assert.Equal(3.42, list[0].Price, 3); + Assert.Equal(10, list[0].RemainingSeconds); + Assert.Equal("OFF", list[1].Status); + Assert.Equal("", list[2].LastBidder); + } + + [Theory] + [InlineData("
", true)] + [InlineData("1764068200*[1;ON;1764068210;342;tizio]", false)] + [InlineData("", false)] + [InlineData("manutenzione", false)] + public void Riconosce_la_pagina_di_login_al_posto_dei_dati(string body, bool expected) + { + Assert.Equal(expected, DataResponseParser.LooksLikeLoginPage(body)); + } +} + +/// bid.php divide il saldo in pagate e gratuite (portato dal legacy). +public class BidResponseTests +{ + [Fact] + public void Il_saldo_e_la_somma_di_pagate_e_gratuite() + { + var r = DataResponseParser.ParseBidResponse(Fixture.Read("bid-ok.txt")); + Assert.True(r.Ok); + Assert.Equal(927, r.PaidRemaining); + Assert.Equal(480, r.FreeRemaining); + Assert.Equal(1407, r.Remaining); + Assert.Equal(8, r.UsedOnAuction); + Assert.Null(r.Error); + } + + [Fact] + public void Una_risposta_corta_da_solo_il_totale_che_conosce() + { + var r = DataResponseParser.ParseBidResponse("ok|12"); + Assert.True(r.Ok); + Assert.Equal(12, r.Remaining); + Assert.Null(r.FreeRemaining); + Assert.Null(r.UsedOnAuction); + } + + [Theory] + [InlineData("error|Timer scaduto
Riprova", "Timer scaduto")] + [InlineData("no|Asta chiusa", "Asta chiusa")] + [InlineData("", "risposta vuota")] + [InlineData("qualcosa di strano", "non riconosciuta")] + [InlineData("alive", "keep-alive")] + public void Gli_errori_arrivano_puliti(string body, string expected) + { + var r = DataResponseParser.ParseBidResponse(body); + Assert.False(r.Ok); + Assert.Contains(expected, r.Error); + Assert.DoesNotContain("
", r.Error); + } +} + +public class AccountParserTests +{ + private const string UserPage = + "" + + "1407 15.00" + + "

una pagina abbastanza lunga da essere vera, con tanto testo in fondo per superare i cento caratteri

"; + + [Fact] + public void La_pagina_del_conto_da_utente_saldo_e_credito() + { + var info = AccountParser.ParseUserPage(UserPage)!; + Assert.Equal("6707664", info.UserId); + Assert.Equal("utente_demo", info.Username); + Assert.Equal(1407, info.RemainingBids); + Assert.Equal(15.00, info.ShopCredit); + } + + [Fact] + public void Senza_dati_la_pagina_non_e_un_conto() + { + Assert.Null(AccountParser.ParseUserPage("" + new string('x', 200) + "Accedi")); + Assert.Null(AccountParser.ParseUserPage("corta")); + } + + [Theory] + [InlineData("125", 125, null)] + [InlineData("125", 125, null)] + [InlineData("utente_demo|1407|15.5|6707664", 1407, "utente_demo")] + public void Il_saldo_leggero_ha_tre_formati(string body, int bids, string? user) + { + var info = AccountParser.ParseCreditsStatus(body)!; + Assert.Equal(bids, info.RemainingBids); + Assert.Equal(user, info.Username); + } + + [Theory] + [InlineData("1", 1)] + [InlineData(" 0 ", 0)] + [InlineData("login", null)] + [InlineData("", null)] + public void Le_aste_da_confermare_distinguono_zero_da_non_lo_so(string body, int? expected) + { + Assert.Equal(expected, AccountParser.ParseAuctionsWon(body)); + } +} + +public class AuctionPageAndUrlTests +{ + private const string Page = """ + Buono Amazon 50 € - Bidoo + + +
  • Spese di transazione: 1,00 €
  • +
  • Limiti di vincita: 1 ogni 30 giorni
  • +
    + + """; + + [Fact] + public void La_pagina_dell_asta_da_valore_spese_e_limite() + { + var info = AuctionPageParser.Parse(Page)!; + Assert.Equal("Buono Amazon 50 €", info.Name); + Assert.Equal(50.00, info.BuyNowPrice); + Assert.Equal(1.00, info.Shipping); + Assert.Equal("1 ogni 30 giorni", info.WinLimit); + Assert.Contains("/products/f123.jpg", info.ImageUrl); + Assert.Equal(26283, info.ProductId); + } + + [Theory] + [InlineData("85559716", "85559716", null)] + [InlineData("https://it.bidoo.com/asta/buono-amazon-50-85559716", "85559716", "Buono Amazon 50")] + [InlineData("https://it.bidoo.com/asta/85559716", "85559716", null)] + [InlineData("https://it.bidoo.com/auction.php?a=Galaxy_S25_Ultra_81204324", "81204324", "Galaxy S25 Ultra")] + public void L_indirizzo_da_id_e_nome(string input, string id, string? name) + { + var parsed = AuctionUrl.Parse(input)!.Value; + Assert.Equal(id, parsed.AuctionId); + Assert.Equal(name, parsed.ProductName); + } + + [Theory] + [InlineData("")] + [InlineData("123")] + [InlineData("https://example.com/asta/85559716")] + [InlineData("non è un indirizzo")] + public void Gli_indirizzi_sbagliati_si_rifiutano(string input) + { + Assert.Null(AuctionUrl.Parse(input)); + } +} + +/// Il listato del catalogo (portato dal legacy). +public class CatalogPageParserTests +{ + private const string Card = """ +
    +
    + + 474 Puntate +
    +
    14,00 €
    +
    + """; + + private const string SecondCard = """ + + """; + + private static string FirstPage() => $$""" + { + "status": "200", + "content": [{{System.Text.Json.JsonSerializer.Serialize(Card)}}, {{System.Text.Json.JsonSerializer.Serialize(SecondCard)}}], + "list": [85559716, 85559720], + "auctions_attributes": { + "85559716": {"data-url":"474_Puntate_85559716","data-freq":5,"data-credit":1,"data-credit-value":474,"data-id-product":26283}, + "85559720": {"data-url":"Frullatore_85559720","data-freq":10,"data-credit":0,"data-credit-value":0,"data-id-product":4947} + } + } + """; + + private static string NextPage() => $$""" + { + "gc": [], "int": [], + "list": [85559716], + "items": [{{System.Text.Json.JsonSerializer.Serialize(Card)}}], + "attributes": { + "85559716": {"data-url":"474_Puntate_85559716","data-freq":5,"data-credit":1,"data-credit-value":474,"data-id-product":26283} + } + } + """; + + [Fact] + public void Legge_la_prima_pagina() + { + var page = CatalogPageParser.ParsePage(FirstPage())!; + Assert.Equal(new[] { "85559716", "85559720" }, page.Ids); + Assert.Equal(2, page.Auctions.Count); + } + + [Fact] + public void Legge_le_pagine_successive_con_gli_altri_nomi_di_campo() + { + var page = CatalogPageParser.ParsePage(NextPage())!; + Assert.Single(page.Ids); + Assert.Equal("474 Puntate", Assert.Single(page.Auctions).Name); + } + + [Fact] + public void Ricava_i_dati_della_scheda() + { + var a = CatalogPageParser.ParsePage(FirstPage())!.Auctions.Single(x => x.AuctionId == "85559716"); + Assert.Equal("474 Puntate", a.Name); + Assert.Equal(5, a.TimerFrequency); + Assert.True(a.IsCreditAuction); + Assert.Equal(474, a.CreditValue); + Assert.Equal(26283, a.ProductId); + Assert.Equal(14.00m, a.BuyNowPrice); + Assert.Equal("https://it.bidoo.com/auction.php?a=474_Puntate_85559716", a.Url); + Assert.Contains("/products/f26283.jpg", a.ImageUrl); + } + + [Fact] + public void Gli_attributi_hanno_la_meglio_sul_markup() + { + var body = """ + {"list": [1], "items": ["
    "], + "attributes": {"1": {"data-freq": 5, "data-id-product": 26283, "data-url": "Cuffie_1"}}} + """; + var a = CatalogPageParser.ParsePage(body)!.Auctions.Single(); + Assert.Equal(5, a.TimerFrequency); + Assert.Equal(26283, a.ProductId); + Assert.Equal("https://it.bidoo.com/auction.php?a=Cuffie_1", a.Url); + } + + [Theory] + [InlineData("
    14,00 €
    ", 14.00)] + [InlineData("
    65,90 €
    ", 65.90)] + [InlineData("
    200,00 €
    ", 200.00)] + [InlineData("
    1.234,00 €
    ", 1234.00)] + [InlineData("
    80 €
    ", 80)] + public void Legge_il_prezzo_del_compra_subito(string markup, double expected) + { + var a = Assert.Single(CatalogPageParser.ParseAuctions($"
    {markup}
    ")); + Assert.Equal((decimal)expected, a.BuyNowPrice); + } + + [Fact] + public void Senza_compra_subito_il_prezzo_resta_ignoto() + { + Assert.Null(Assert.Single(CatalogPageParser.ParseAuctions("
    nessun riquadro
    ")).BuyNowPrice); + } + + [Fact] + public void Pagina_vuota_e_diversa_da_risposta_incomprensibile() + { + var end = CatalogPageParser.ParsePage("""{"gc":[],"int":[],"list":[],"items":[]}""")!; + Assert.Empty(end.Ids); + Assert.Empty(end.Auctions); + } + + [Theory] + [InlineData("")] + [InlineData("Manutenzione in corso")] + [InlineData("{\"status\":\"500\"}")] + [InlineData("[1,2,3]")] + public void Risposta_non_riconosciuta_restituisce_null(string body) + { + Assert.Null(CatalogPageParser.ParsePage(body)); + } + + [Fact] + public void Un_id_senza_scheda_resta_comunque_nell_elenco() + { + var page = CatalogPageParser.ParsePage("""{"list": [1, 2], "items": ["
    "]}""")!; + Assert.Equal(new[] { "1", "2" }, page.Ids); + Assert.Single(page.Auctions); + } + + [Fact] + public void Le_entita_html5_nei_nomi_si_decodificano() + { + Assert.Equal("Cuffie - Pro + Max!", CatalogPageParser.DecodeHtml("Cuffie &dash; Pro + Max!")); + } +} + +public class ReferencesTests +{ + [Fact] + public void I_valori_di_fabbrica_hanno_tutti_gli_indirizzi() + { + var r = BidooReferences.Default; + Assert.Equal("https://it.bidoo.com", r.BaseUrl); + Assert.Equal("https://it.bidoo.com/data.php?ALL=85559716&LISTID=0", r.Url(r.Endpoints.AuctionData, ("id", "85559716"))); + Assert.Equal("https://it.bidoo.com/bid.php?AID=85559716&sup=0&shock=0", r.Url(r.Endpoints.Bid, ("id", "85559716"))); + Assert.Equal("__stattrb", r.Recognizers.SessionCookie); + Assert.Equal(60, r.Timing.PreCheckMs); + Assert.Equal(3, r.Limits.BidLaneConnections); + } + + [Fact] + public void Il_file_cambia_solo_le_voci_che_contiene() + { + var r = BidooReferences.Parse(""" + { + // commento ammesso + "baseUrl": "http://127.0.0.1:5555", + "endpoints": { "bid": "/altro.php?id={id}" }, + } + """); + Assert.Equal("http://127.0.0.1:5555", r.BaseUrl); + Assert.Equal("/altro.php?id={id}", r.Endpoints.Bid); + Assert.Equal("/data.php?ALL={id}&LISTID=0", r.Endpoints.AuctionData); + Assert.NotEmpty(r.Recognizers.RemainingBids); + } + + [Fact] + public void Un_espressione_sbagliata_non_fa_cadere_nulla() + { + Assert.Null(BidooReferences.FirstGroup("testo", "([a-z")); + } + + [Fact] + public void Il_file_si_rilegge_a_caldo_e_un_file_rotto_lascia_il_precedente() + { + using var dir = new TempDir(); + using var provider = new ReferencesProvider(dir.Path, null, watch: false); + Assert.True(File.Exists(provider.FilePath)); + Assert.Equal("https://it.bidoo.com", provider.Current.BaseUrl); + } +} + +public class NetTests +{ + [Fact] + public void I_cookie_rinnovati_dal_server_sostituiscono_i_vecchi() + { + var merged = CookieText.Merge("__stattrb=vecchio; PHPSESSID=abc; x=1", + new[] { "__stattrb=nuovo; path=/; HttpOnly", "x=deleted; expires=Thu, 01 Jan 1970 00:00:00 GMT", "y=2; path=/" }); + Assert.Equal("__stattrb=nuovo; PHPSESSID=abc; y=2", merged); + Assert.True(CookieText.Contains(merged, "__stattrb")); + Assert.False(CookieText.Contains(merged, "x")); + } + + [Fact] + public void Il_token_bucket_lascia_una_riserva_al_polling() + { + var bucket = new TokenBucket(10) { BackgroundReserve = 0.5 }; // capacità 10, riserva 5 + var backgroundFree = 0; + for (var i = 0; i < 10; i++) if (bucket.Reserve(background: true) == 0) backgroundFree++; + Assert.True(backgroundFree <= 5); + + // Il polling trova comunque gettoni subito. + Assert.Equal(0, new TokenBucket(10).Reserve(background: false)); + } + + [Fact] + public void Senza_limite_non_si_aspetta_mai() + { + var bucket = new TokenBucket(0); + for (var i = 0; i < 1000; i++) Assert.Equal(0, bucket.Reserve(background: true)); + } + + [Fact] + public void Le_latenze_danno_i_percentili() + { + var stats = new LatencyStats(100); + for (var i = 1; i <= 100; i++) stats.Add(i); + Assert.Equal(50, stats.Percentile(0.5)); + Assert.Equal(99, stats.Percentile(0.99)); + Assert.Equal(50.5, stats.Average()); + } +}