M2: protocollo di Bidoo, catalogo e trasporto con corsia per le puntate
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
13f2413320
commit
636e7e1251
21 files changed
+2870
-3
No files matched your search
@@ -0,0 +1,81 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace BidooBidBot.Bidoo;
|
||||
|
||||
/// <summary>Ciò che si sa del conto Bidoo.</summary>
|
||||
public sealed record AccountInfo(string? UserId, string? Username, int? RemainingBids, double? ShopCredit);
|
||||
|
||||
/// <summary>
|
||||
/// Legge le pagine del conto: <c>buy_bids.php</c> (pagina intera con utente, saldo e
|
||||
/// credito), <c>update_credits_status.php</c> (saldo leggero, tre formati osservati),
|
||||
/// <c>check_auctions_won.php</c> (un numero). Pura, sotto test; le espressioni vengono dai
|
||||
/// riferimenti.
|
||||
/// </summary>
|
||||
public static class AccountParser
|
||||
{
|
||||
/// <summary>
|
||||
/// <c>buy_bids.php</c>. Null se la pagina non contiene nessuno dei dati: cookie scaduto o
|
||||
/// pagina di login.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>update_credits_status.php?submit=1</c>: un numero, oppure
|
||||
/// <c><span id="bids_count">N</span></c>, oppure <c>utente|puntate|credito|id</c>.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
|
||||
namespace BidooBidBot.Bidoo;
|
||||
|
||||
/// <summary>Quello che la pagina di un'asta dice del prodotto.</summary>
|
||||
public sealed record AuctionPageInfo(
|
||||
string? Name, double? BuyNowPrice, double? Shipping, string? WinLimit, string? ImageUrl, int? ProductId);
|
||||
|
||||
/// <summary>
|
||||
/// Legge la pagina dell'asta (<c>auction.php?a=…</c>): nome, «Compralo Ora» (il valore di
|
||||
/// listino), spese di spedizione o di transazione, limite di vincita, foto. Portato da
|
||||
/// <c>ProductValueCalculator.ExtractProductInfo</c> del legacy; le espressioni stanno nei
|
||||
/// riferimenti.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Un prezzo all'italiana («20,00») o col punto.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dall'indirizzo di un'asta (o dal solo id) all'id numerico e a un nome provvisorio.
|
||||
/// Formati: <c>/asta/nome-prodotto-81204324</c>, <c>/asta/81204324</c>,
|
||||
/// <c>auction.php?a=Galaxy_S25_81204324</c>, oppure l'id nudo.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>«Galaxy_S25_Ultra_81204324» o «galaxy-s25-ultra-81204324» → «Galaxy S25 Ultra».</summary>
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
namespace BidooBidBot.Bidoo;
|
||||
|
||||
/// <summary>Stato di un'asta secondo il server.</summary>
|
||||
public enum AuctionStatus
|
||||
{
|
||||
Unknown,
|
||||
|
||||
/// <summary>In corso: ON con almeno un puntatore.</summary>
|
||||
Running,
|
||||
|
||||
/// <summary>STOP: Bidoo ferma le aste di notte. Non è il nostro «Osserva».</summary>
|
||||
Paused,
|
||||
|
||||
EndedWon,
|
||||
EndedLost,
|
||||
|
||||
/// <summary>ON senza puntate e cronometro corto: sta per cominciare.</summary>
|
||||
Pending,
|
||||
|
||||
/// <summary>ON senza puntate e cronometro oltre la soglia: programmata più in là.</summary>
|
||||
Scheduled,
|
||||
|
||||
/// <summary>OFF senza vincitore.</summary>
|
||||
Closed
|
||||
}
|
||||
|
||||
/// <summary>Una fotografia dell'asta presa da <c>data.php</c>.</summary>
|
||||
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 ──────────────────────────────────
|
||||
|
||||
/// <summary>Secondo unix dichiarato dal server in questa risposta.</summary>
|
||||
public long ServerUnixSeconds { get; set; }
|
||||
|
||||
/// <summary>Secondo unix in cui scade il ciclo, secondo il server.</summary>
|
||||
public long ExpiryUnixSeconds { get; set; }
|
||||
|
||||
/// <summary>Tick di Stopwatch alla ricezione (monotono).</summary>
|
||||
public long ReceivedTicks { get; set; }
|
||||
|
||||
// ── Puntate del vincitore (solo ad asta conclusa) ─────────────────
|
||||
|
||||
public int? WinnerBidsPaid { get; set; }
|
||||
public int? WinnerBidsFree { get; set; }
|
||||
|
||||
/// <summary>Il numero che il sito mostra come «Puntate utilizzate». Null se l'asta non è conclusa.</summary>
|
||||
public int? WinnerBidsTotal =>
|
||||
WinnerBidsPaid.HasValue || WinnerBidsFree.HasValue ? (WinnerBidsPaid ?? 0) + (WinnerBidsFree ?? 0) : null;
|
||||
|
||||
/// <summary>Le ultime puntate (al massimo 50), dalla più recente.</summary>
|
||||
public List<BidHistoryEntry>? RecentBidsHistory { get; set; }
|
||||
|
||||
public bool IsTerminal => Status is AuctionStatus.EndedWon or AuctionStatus.EndedLost or AuctionStatus.Closed;
|
||||
}
|
||||
|
||||
/// <summary>Una puntata come la riporta lo storico di <c>data.php</c>.</summary>
|
||||
public sealed class BidHistoryEntry
|
||||
{
|
||||
/// <summary>Puntata dell'autopuntata del sito (codice 3).</summary>
|
||||
public const string TypeAuto = "Auto";
|
||||
|
||||
/// <summary>Puntata fatta a mano (codice 1).</summary>
|
||||
public const string TypeManual = "Manuale";
|
||||
|
||||
/// <summary>Il tipo non lo ha detto il server (puntata ricostruita da un cambio di prezzo).</summary>
|
||||
public const string TypeUnknown = "";
|
||||
|
||||
public decimal Price { get; set; }
|
||||
public string Username { get; set; } = "";
|
||||
|
||||
/// <summary>Istante unix dichiarato dal server (secondi interi).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Il prezzo in centesimi: su Bidoo è anche il numero d'ordine della puntata nell'asta.</summary>
|
||||
public int PriceCents => (int)Math.Round(Price * 100);
|
||||
}
|
||||
|
||||
/// <summary>Cosa dice <c>bid.php</c> dopo una puntata.</summary>
|
||||
public readonly record struct BidResponse(
|
||||
bool Ok,
|
||||
int? PaidRemaining,
|
||||
int? FreeRemaining,
|
||||
int? FreeUsedOnAuction,
|
||||
int? PaidUsedOnAuction,
|
||||
string? Error,
|
||||
bool KeepAlive = false)
|
||||
{
|
||||
/// <summary>Puntate residue totali: a pagamento più gratuite.</summary>
|
||||
public int? Remaining => PaidRemaining is { } p && FreeRemaining is { } f ? p + f : PaidRemaining;
|
||||
|
||||
/// <summary>Puntate usate su questa asta, di entrambi i tipi.</summary>
|
||||
public int? UsedOnAuction => PaidUsedOnAuction is { } p ? p + (FreeUsedOnAuction ?? 0) : FreeUsedOnAuction;
|
||||
}
|
||||
|
||||
/// <summary>Una riga della risposta a più aste (<c>data.php?LISTID=…</c>).</summary>
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using BidooBidBot.Net;
|
||||
|
||||
namespace BidooBidBot.Bidoo;
|
||||
|
||||
/// <summary>Esito di un'interrogazione di data.php.</summary>
|
||||
public sealed record PollResult(AuctionState? State, HttpOutcome Outcome, string? Error);
|
||||
|
||||
/// <summary>Esito di una puntata.</summary>
|
||||
public sealed record BidAttempt(
|
||||
bool Success,
|
||||
BidResponse Response,
|
||||
int LatencyMs,
|
||||
string? Error,
|
||||
long SentTicks,
|
||||
bool UsedFallback,
|
||||
string RawBody);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="SessionInvalid"/>.
|
||||
/// </summary>
|
||||
public sealed class BidooApi
|
||||
{
|
||||
private readonly BidooTransport _transport;
|
||||
private readonly BidLane _lane;
|
||||
private readonly Func<BidooReferences> _refs;
|
||||
|
||||
public BidooApi(BidooTransport transport, BidLane lane, Func<BidooReferences> refs)
|
||||
{
|
||||
_transport = transport;
|
||||
_lane = lane;
|
||||
_refs = refs;
|
||||
}
|
||||
|
||||
public BidooTransport Transport => _transport;
|
||||
public BidLane Lane => _lane;
|
||||
public BidooReferences References => _refs();
|
||||
|
||||
/// <summary>L'utente collegato, per riconoscere le proprie puntate.</summary>
|
||||
public string? Username { get; set; }
|
||||
|
||||
/// <summary>La sessione non vale più (403 o pagina di login). Il testo dice cosa si è visto.</summary>
|
||||
public event Action<string>? 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);
|
||||
|
||||
/// <summary>Una interrogazione di data.php per un'asta.</summary>
|
||||
public async Task<PollResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// La puntata: prima sulla corsia dedicata; se questa fallisce per un errore di rete e
|
||||
/// mancano ancora più di <paramref name="retryIfMsLeft"/> ms, una sola volta sul pool
|
||||
/// normale (priorità critica). Un «no» di Bidoo non si ritenta mai.
|
||||
/// </summary>
|
||||
public async Task<BidAttempt> PlaceBidAsync(string auctionId, string? auctionUrl, Func<double>? 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);
|
||||
}
|
||||
|
||||
/// <summary><c>buy_bids.php</c>: utente, saldo, credito. Null se la sessione non vale.</summary>
|
||||
public async Task<AccountInfo?> 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;
|
||||
}
|
||||
|
||||
/// <summary><c>update_credits_status.php</c>: il saldo leggero.</summary>
|
||||
public async Task<AccountInfo?> 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);
|
||||
}
|
||||
|
||||
/// <summary>Aste vinte da confermare. Null = non lo so.</summary>
|
||||
public async Task<int?> 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;
|
||||
}
|
||||
|
||||
/// <summary>La pagina dell'asta: nome, Compralo Ora, spedizione, limite di vincita, foto.</summary>
|
||||
public async Task<AuctionPageInfo?> 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;
|
||||
}
|
||||
|
||||
/// <summary>Stati di molte aste in una richiesta (<c>data.php?LISTID=…</c>).</summary>
|
||||
public async Task<List<ListEntry>> GetListAsync(IReadOnlyList<string> auctionIds, CancellationToken ct)
|
||||
{
|
||||
var refs = _refs();
|
||||
var result = new List<ListEntry>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Millisecondi trascorsi da un tick di Stopwatch.</summary>
|
||||
public static double MsSince(long ticks) => (Stopwatch.GetTimestamp() - ticks) * 1000.0 / Stopwatch.Frequency;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <c>/config/riferimenti/bidoo.json</c> senza ricompilare.
|
||||
/// </summary>
|
||||
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<string> RemainingBids { get; set; } = new();
|
||||
public string ShopCredit { get; set; } = "";
|
||||
public string CreditsCount { get; set; } = "";
|
||||
public List<string> LoginPageMarkers { get; set; } = new();
|
||||
public string SessionCookie { get; set; } = "__stattrb";
|
||||
public string AuctionTitle { get; set; } = "";
|
||||
public string AuctionTitleSuffix { get; set; } = "";
|
||||
public List<string> ProductValue { get; set; } = new();
|
||||
public List<string> 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<string> 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à ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Indirizzo completo da un modello con segnaposto <c>{id}</c>, <c>{ids}</c>…</summary>
|
||||
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));
|
||||
|
||||
/// <summary>Lo User-Agent da usare: quello del file, quello della sessione, o quello di ripiego.</summary>
|
||||
public string EffectiveUserAgent(string? sessionUserAgent) =>
|
||||
!string.IsNullOrWhiteSpace(UserAgent) ? UserAgent
|
||||
: !string.IsNullOrWhiteSpace(sessionUserAgent) ? sessionUserAgent!
|
||||
: DefaultUserAgent;
|
||||
|
||||
// ── Espressioni ──────────────────────────────────────────────────────
|
||||
|
||||
private static readonly ConcurrentDictionary<string, Regex> RegexCache = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>Il primo gruppo della prima espressione che trova qualcosa.</summary>
|
||||
public static string? FirstGroup(string? text, IEnumerable<string> 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
|
||||
};
|
||||
|
||||
/// <summary>Il testo dei valori di fabbrica incorporati nel binario.</summary>
|
||||
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<BidooReferences> LazyDefault = new(() => Parse(null));
|
||||
|
||||
/// <summary>I valori di fabbrica, senza file: per i test e per chi non ha ancora /config.</summary>
|
||||
public static BidooReferences Default => LazyDefault.Value;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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<BidooReferences>(JsonOptions)!;
|
||||
}
|
||||
|
||||
/// <summary>Unione profonda: gli oggetti si fondono, tutto il resto (liste comprese) si sostituisce.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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é.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>Scatta quando un file modificato è stato letto e applicato.</summary>
|
||||
public event Action<BidooReferences>? 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();
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
using System.Globalization;
|
||||
using BidooBidBot.Logging;
|
||||
using BidooBidBot.Net;
|
||||
|
||||
namespace BidooBidBot.Bidoo;
|
||||
|
||||
/// <summary>
|
||||
/// Il catalogo pubblico di Bidoo (portato da <c>Services/BidooCatalogClient</c> del legacy):
|
||||
/// categorie, listato paginato a scorrimento, aggiornamento prezzi in massa. Non richiede
|
||||
/// l'accesso.
|
||||
///
|
||||
/// <para>La paginazione del sito: prima pagina <c>GET get_auctions.php?tab=T&tag=G</c>,
|
||||
/// seguenti <c>POST get_auction_updates.php</c> con <c>view</c> = tutti gli id già visti.
|
||||
/// Niente numero di pagina né cursore: la fine si riconosce solo da una pagina vuota.</para>
|
||||
/// </summary>
|
||||
public sealed class CatalogClient
|
||||
{
|
||||
private readonly BidooTransport _http;
|
||||
private readonly Func<BidooReferences> _refs;
|
||||
private readonly AppLog? _log;
|
||||
private readonly Dictionary<string, (DateTime At, List<CatalogAuction> Auctions)> _cache = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, int> _lastReported = new(StringComparer.Ordinal);
|
||||
private List<CatalogCategory>? _categories;
|
||||
private DateTime _categoriesAt = DateTime.MinValue;
|
||||
|
||||
public CatalogClient(BidooTransport http, Func<BidooReferences> refs, AppLog? log)
|
||||
{
|
||||
_http = http;
|
||||
_refs = refs;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
public static readonly IReadOnlyList<CatalogCategory> SpecialCategories = new[]
|
||||
{
|
||||
CatalogCategory.AllAuctions,
|
||||
new CatalogCategory(1, 0, "", "Aste di puntate", true),
|
||||
new CatalogCategory(5, 0, "", "Aste manuali", true)
|
||||
};
|
||||
|
||||
/// <summary>Le categorie di ripiego, se la pagina principale non si legge.</summary>
|
||||
public static readonly IReadOnlyList<CatalogCategory> 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<List<CatalogCategory>> 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<CatalogCategory>(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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fino a <paramref name="maxAuctions"/> aste della categoria, pagina dopo pagina. Il
|
||||
/// listato è in ordine di scadenza: fermarsi al tetto non taglia nulla di urgente.
|
||||
/// </summary>
|
||||
public async Task<List<CatalogAuction>> 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<CatalogAuction>();
|
||||
var seen = new HashSet<string>(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<bool> CollectPagesAsync(CatalogCategory category, List<CatalogAuction> all, HashSet<string> 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<string>();
|
||||
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<CatalogAuction> all, HashSet<string> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Prezzo, ultimo puntatore e timer di molte aste, a blocchi (60 per richiesta).</summary>
|
||||
public async Task UpdateStatesAsync(IReadOnlyList<CatalogAuction> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace BidooBidBot.Bidoo;
|
||||
|
||||
/// <summary>Un'asta come compare nel catalogo pubblico di Bidoo.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Categoria del catalogo: le tre speciali (tab) e quelle per tag.</summary>
|
||||
public sealed record CatalogCategory(int TabId, int TagId, string Slug, string DisplayName, bool IsSpecial)
|
||||
{
|
||||
/// <summary>Chiave stabile per cache e interfaccia.</summary>
|
||||
public string Key => IsSpecial ? $"s{TabId}" : $"t{TagId}";
|
||||
|
||||
public static readonly CatalogCategory AllAuctions = new(3, 0, "", "Tutte le aste", true);
|
||||
}
|
||||
|
||||
/// <summary>Una pagina di listato: le schede interpretate e gli id così come arrivano.</summary>
|
||||
public sealed record CatalogPage(List<CatalogAuction> Auctions, List<string> Ids);
|
||||
|
||||
/// <summary>
|
||||
/// Interpreta le risposte del listato (portato dal legacy). Le due chiamate hanno la stessa
|
||||
/// struttura con nomi diversi: schede in <c>content</c> (prima pagina) o <c>items</c>
|
||||
/// (successive), attributi in <c>auctions_attributes</c> o <c>attributes</c>, id sempre in
|
||||
/// <c>list</c>. Distingue «pagina vuota, siamo in fondo» da «risposta incomprensibile».
|
||||
/// </summary>
|
||||
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<string>(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;
|
||||
|
||||
/// <summary>I valori strutturati vincono su quelli letti dal markup.</summary>
|
||||
private static void ApplyAttributes(List<CatalogAuction> 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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Le schede da un blocco di HTML (listato o vecchia pagina intera).</summary>
|
||||
public static List<CatalogAuction> ParseAuctions(string html, BidooReferences? refs = null)
|
||||
{
|
||||
refs ??= BidooReferences.Default;
|
||||
var r = refs.Recognizers;
|
||||
var auctions = new List<CatalogAuction>();
|
||||
var seen = new HashSet<string>(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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>Entità HTML 4 più quelle HTML5 che compaiono nei nomi (&dash;, &plus;…).</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Le categorie per tag dalla pagina principale.</summary>
|
||||
public static List<CatalogCategory> ParseCategories(string? html, BidooReferences? refs = null)
|
||||
{
|
||||
refs ??= BidooReferences.Default;
|
||||
var list = new List<CatalogCategory>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace BidooBidBot.Bidoo;
|
||||
|
||||
/// <summary>
|
||||
/// Traduce le risposte di <c>data.php</c> e <c>bid.php</c>. 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.
|
||||
///
|
||||
/// <para>Formato: <c>serverTs*[core,storico]</c>. <c>core</c> =
|
||||
/// <c>id;STATO;scadenza;prezzoCent;utente</c>; nelle aste concluse porta in coda
|
||||
/// <c>|pagate|gratis|super|shock|manuali|automatiche|</c>. La <b>virgola</b> separa core e
|
||||
/// storico; il <c>|</c> separa i record dello storico (<c>prezzoCent;utente;istante;tipo</c>).
|
||||
/// Tagliare sul primo <c>|</c> faceva sparire la puntata più recente (difetto corretto nel
|
||||
/// legacy il 2026-08-01).</para>
|
||||
/// </summary>
|
||||
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 };
|
||||
}
|
||||
|
||||
/// <summary>Interpreta una risposta di data.php per una sola asta.</summary>
|
||||
/// <param name="username">Utente corrente, per riconoscere le proprie puntate.</param>
|
||||
/// <param name="maxHistoryEntries">Tetto alle puntate lette dallo storico (0 = tutte).</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puntate spese dal vincitore: <c>pagate|gratis|super|shock|manuali|automatiche|</c>.
|
||||
/// È l'unica fonte attendibile (lo storico si ferma alle ultime cinquanta).
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// La risposta di <c>bid.php</c>: <c>ok|pagateResidue|gratisResidue|gratisUsateQui|pagateUsateQui|0|idAsta|0|0</c>.
|
||||
/// Il secondo campo NON è il saldo totale. Errori: <c>error|messaggio</c> o <c>no|messaggio</c>,
|
||||
/// a volte con HTML; <c>alive</c> è un keep-alive, non una conferma.
|
||||
/// </summary>
|
||||
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)}");
|
||||
}
|
||||
|
||||
/// <summary>ON = in corso, OFF = conclusa, STOP = sospesa (Bidoo ferma le aste di notte).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Storico: <c>prezzoCent;utente;istanteUnix;tipo</c> separati da <c>|</c>; tipo 3 = automatica, 1 = manuale.</summary>
|
||||
public static List<BidHistoryEntry>? 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<BidHistoryEntry>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// La risposta a più aste: <c>serverTs*(id;STATO;scadenza;prezzoCent;utente#id2;…)</c>.
|
||||
/// Le righe che non si leggono si saltano.
|
||||
/// </summary>
|
||||
public static List<ListEntry> ParseList(string? response, BidooReferences? refs = null)
|
||||
{
|
||||
refs ??= BidooReferences.Default;
|
||||
var p = refs.Parsing;
|
||||
var list = new List<ListEntry>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
@@ -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": [
|
||||
"<span[^>]*id=\"divSaldoBidMobile\"[^>]*>(\\d+)</span>",
|
||||
"<span[^>]*id=\"divSaldoBidBottom\"[^>]*>(\\d+)</span>",
|
||||
"<span[^>]*id=\"divSaldoBid\"[^>]*>(\\d+)</span>"
|
||||
],
|
||||
"shopCredit": "<span[^>]*class=\"cbstotal\"[^>]*>([\\d.]+)</span>",
|
||||
"creditsCount": "<span[^>]*id=\"bids_count\"[^>]*>(\\d+)</span>",
|
||||
"loginPageMarkers": [ "login.php" ],
|
||||
"sessionCookie": "__stattrb",
|
||||
|
||||
"auctionTitle": "<title>([^<]+)</title>",
|
||||
"auctionTitleSuffix": " - Bidoo",
|
||||
"productValue": [
|
||||
"<span[^>]*class=\"[^\"]*product-value[^\"]*\"[^>]*>.*?Valore:.*?<span[^>]*>([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:.*?<span[^>]*>([0-9]+[,.]?[0-9]*)\\s*€",
|
||||
"Spese\\s+di\\s+transazione:.*?<span[^>]*>([0-9]+[,.]?[0-9]*)\\s*€"
|
||||
],
|
||||
"winLimit": "Limiti\\s+di\\s+vincita:.*?<span[^>]*>([^<]+)</span>",
|
||||
"productImage": "(https?://[^\"'\\s]+/products/[^\"'\\s]+\\.(?:jpg|jpeg|png|webp))",
|
||||
"productId": "data-id-product=\"(\\d+)\"",
|
||||
|
||||
"catalogCard": "<div[^>]+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": "<img[^>]+src=\"(https?://[^\"]+/products/[^\"]+)\"",
|
||||
"catalogName": "<a[^>]+class=\"name[^\"]*\"[^>]*>([^<]+)</a>",
|
||||
"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+\"><span[^>]*>([^<]+)</span>",
|
||||
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using System.Net;
|
||||
using BidooBidBot.Bidoo;
|
||||
|
||||
namespace BidooBidBot.Net;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
///
|
||||
/// <para>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.</para>
|
||||
/// </summary>
|
||||
public sealed class BidLane : IDisposable
|
||||
{
|
||||
private readonly BidooTransport _transport;
|
||||
private readonly Func<BidooReferences> _refs;
|
||||
private readonly HttpClient _client;
|
||||
private readonly Timer? _keepAlive;
|
||||
private long _bids;
|
||||
private long _failures;
|
||||
|
||||
public BidLane(BidooTransport transport, Func<BidooReferences> 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);
|
||||
|
||||
/// <summary>Latenze delle puntate (andata e ritorno di bid.php).</summary>
|
||||
public LatencyStats BidLatency { get; } = new(300);
|
||||
|
||||
/// <summary>
|
||||
/// Invia la puntata sulla corsia. La richiesta ha le stesse intestazioni del trasporto
|
||||
/// (cookie, User-Agent), più Origin e Referer alla pagina dell'asta.
|
||||
/// </summary>
|
||||
public async Task<HttpOutcome> 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;
|
||||
}
|
||||
|
||||
/// <summary>Tiene aperte le connessioni della corsia con una richiesta leggera.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Text;
|
||||
using BidooBidBot.Bidoo;
|
||||
|
||||
namespace BidooBidBot.Net;
|
||||
|
||||
/// <summary>
|
||||
/// Trasporto HTTP verso Bidoo, dimensionato per un flusso continuo di richieste
|
||||
/// (specifica §6.4, portato da <c>Net/BidooHttpClient</c> del legacy).
|
||||
///
|
||||
/// <list type="bullet">
|
||||
/// <item>Un solo <see cref="SocketsHttpHandler"/> con pool ampio e connessioni calde,
|
||||
/// HTTP/2 con ripiego, decompressione automatica, cookie a mano.</item>
|
||||
/// <item>User-Agent: lo stesso del browser dell'accesso assistito, salvato con la sessione.</item>
|
||||
/// <item>Token bucket (40 richieste/s di fabbrica) con riserva per il polling, semaforo di
|
||||
/// concorrenza; le richieste <see cref="RequestPriority.Critical"/> saltano entrambi.</item>
|
||||
/// <item>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.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public sealed class BidooTransport : IDisposable
|
||||
{
|
||||
private readonly Func<BidooReferences> _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<BidooReferences> 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);
|
||||
}
|
||||
|
||||
/// <summary>Un handler come serve a Bidoo: pool caldo, HTTP/2, cookie gestiti a mano.</summary>
|
||||
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> { 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);
|
||||
|
||||
/// <summary>Latenze delle richieste di polling andate a buon fine.</summary>
|
||||
public LatencyStats PollLatency { get; } = new(300);
|
||||
|
||||
public string Cookie => _cookie;
|
||||
public bool HasCookie => _cookie.Length > 0;
|
||||
public string UserAgent => _refs().EffectiveUserAgent(_sessionUserAgent);
|
||||
|
||||
/// <summary>Scatta quando il server ha rinnovato un cookie della sessione (Set-Cookie).</summary>
|
||||
public event Action<string>? CookieChanged;
|
||||
|
||||
public void SetSession(string? cookie, string? userAgent)
|
||||
{
|
||||
_cookie = cookie?.Trim() ?? "";
|
||||
_sessionUserAgent = userAgent?.Trim() ?? "";
|
||||
}
|
||||
|
||||
/// <summary>Limiti di ritmo a caldo, senza ricreare il trasporto.</summary>
|
||||
public void Configure(double requestsPerSecond) => _limiter.SetRate(requestsPerSecond);
|
||||
|
||||
/// <summary>Millisecondi di freno ancora da scontare. Zero quando si va liberi.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Una GET completa di cookie, User-Agent e intestazioni di contesto.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Una POST con corpo già codificato (application/x-www-form-urlencoded).</summary>
|
||||
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('/') + "/");
|
||||
}
|
||||
|
||||
/// <summary>Invia rispettando ritmo, freno e concorrenza (salvo le Critical).</summary>
|
||||
public async Task<HttpOutcome> 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// La richiesta vera e propria: corpo, stato, latenza misurata con Stopwatch, cookie
|
||||
/// rinnovati dal server. Usata anche dalla corsia delle puntate.
|
||||
/// </summary>
|
||||
public async Task<HttpOutcome> 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private void MergeCookies(IEnumerable<string> 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 */ }
|
||||
}
|
||||
|
||||
/// <summary>Apre in anticipo qualche connessione, così le prime richieste non pagano TCP+TLS.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Operazioni sulla stringa dei cookie («a=1; b=2»). Pura, sotto test.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Applica le intestazioni Set-Cookie di una risposta alla stringa corrente.</summary>
|
||||
public static string Merge(string current, IEnumerable<string> 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace BidooBidBot.Net;
|
||||
|
||||
/// <summary>Priorità di una richiesta. Le puntate non si accodano mai dietro al polling.</summary>
|
||||
public enum RequestPriority
|
||||
{
|
||||
/// <summary>Catalogo, dati del conto, recuperi storici: cedono il passo, lasciano una riserva di gettoni.</summary>
|
||||
Background = 0,
|
||||
|
||||
/// <summary>Polling delle aste.</summary>
|
||||
Normal,
|
||||
|
||||
/// <summary>Salta limitatore, freno e coda. Riservato alle puntate.</summary>
|
||||
Critical
|
||||
}
|
||||
|
||||
/// <summary>Esito di una richiesta HTTP: corpo, stato, latenza, istante di ricezione.</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>Tick di Stopwatch all'arrivo della risposta (monotono).</summary>
|
||||
public long ReceivedTicks { get; init; }
|
||||
|
||||
/// <summary>Tick di Stopwatch alla partenza: con <see cref="ReceivedTicks"/> dà il giro completo.</summary>
|
||||
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)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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++;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Il percentile richiesto (0-1); null senza campioni.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace BidooBidBot.Net;
|
||||
|
||||
/// <summary>
|
||||
/// Token bucket a rilascio continuo: un gettone per richiesta, e si aspetta solo il tempo
|
||||
/// di rigenerarlo. Nessun timer, nessun thread.
|
||||
///
|
||||
/// <para>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.</para>
|
||||
/// </summary>
|
||||
public sealed class TokenBucket
|
||||
{
|
||||
private readonly object _sync = new();
|
||||
private double _capacity;
|
||||
private double _rate;
|
||||
private double _tokens;
|
||||
private long _lastTicks;
|
||||
|
||||
/// <summary>Quota di capacità che le richieste di fondo non possono toccare.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Millisecondi da aspettare prima di poter partire (e prenota il gettone).</summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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}");
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
error|Timer scaduto<br>Riprova
|
||||
@@ -0,0 +1 @@
|
||||
ok|927|480|3|5|0|1234567|0|0
|
||||
@@ -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]
|
||||
@@ -0,0 +1 @@
|
||||
1785597356*[95755813;ON;1785597364;4;kikisi9;1,4;kikisi9;1785597356;1|3;casmeride;1785597348;1|2;kikisi9;1785597340;1]
|
||||
@@ -0,0 +1 @@
|
||||
1764068200*(95216992;ON;1764068210;342;fedekikka2323#95216993;OFF;1764068100;120;tizio#95216994;ON;1764075000;1;)
|
||||
@@ -0,0 +1 @@
|
||||
1785597337*[95760550;ON;1785597351;1;;,]
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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("<html><form action=\"login.php\">", true)]
|
||||
[InlineData("1764068200*[1;ON;1764068210;342;tizio]", false)]
|
||||
[InlineData("", false)]
|
||||
[InlineData("<html>manutenzione</html>", false)]
|
||||
public void Riconosce_la_pagina_di_login_al_posto_dei_dati(string body, bool expected)
|
||||
{
|
||||
Assert.Equal(expected, DataResponseParser.LooksLikeLoginPage(body));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>bid.php divide il saldo in pagate e gratuite (portato dal legacy).</summary>
|
||||
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<br>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("<br>", r.Error);
|
||||
}
|
||||
}
|
||||
|
||||
public class AccountParserTests
|
||||
{
|
||||
private const string UserPage =
|
||||
"<html><head><script>BidooCnf.userObj.id = '6707664'; BidooCnf.userObj.username = 'utente_demo';</script></head>" +
|
||||
"<body><span id=\"divSaldoBidMobile\">1407</span> <span class=\"cbstotal\">15.00</span>" +
|
||||
"<p>una pagina abbastanza lunga da essere vera, con tanto testo in fondo per superare i cento caratteri</p></body></html>";
|
||||
|
||||
[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("<html>" + new string('x', 200) + "<a href=\"login.php\">Accedi</a></html>"));
|
||||
Assert.Null(AccountParser.ParseUserPage("corta"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("125", 125, null)]
|
||||
[InlineData("<span id=\"bids_count\">125</span>", 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("<html>login</html>", 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 = """
|
||||
<html><head><title>Buono Amazon 50 € - Bidoo</title></head><body>
|
||||
<img src="https://cdn.bidoo.com/products/f123.jpg">
|
||||
<span class="text-muted product-value"><span class="hidden-xs">Valore: </span><span class="product-value hidden-xs">50,00 €</span></span>
|
||||
<li>Spese di transazione: <span>1,00 €</span></li>
|
||||
<li>Limiti di vincita: <span>1 ogni 30 giorni</span></li>
|
||||
<div data-id-product="26283"></div>
|
||||
</body></html>
|
||||
""";
|
||||
|
||||
[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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Il listato del catalogo (portato dal legacy).</summary>
|
||||
public class CatalogPageParserTests
|
||||
{
|
||||
private const string Card = """
|
||||
<div id="divAsta85559716"
|
||||
class="live- auction- col-lg-2 col-md-3 col-sm-4 col-xs-6"
|
||||
data-id="85559716" data-url="474_Puntate_85559716" data-freq="5"
|
||||
data-biddable="1" data-level="0" data-type="0"
|
||||
data-credit="1" data-credit-value="474" data-id-product="26283">
|
||||
<div class="auction photo">
|
||||
<img class="img_small" src="https://cdn.example.com/products/f26283.jpg" width="160">
|
||||
<a href='auction.php?a=474_Puntate_85559716' class="name " title="">474 Puntate</a>
|
||||
</div>
|
||||
<div class="buynow-btn"><div class="btn-rapid buy-rapid-now">14,00 €</div></div>
|
||||
</div>
|
||||
""";
|
||||
|
||||
private const string SecondCard = """
|
||||
<div id="divAsta85559720" data-id="85559720" data-url="Frullatore_85559720"
|
||||
data-freq="10" data-credit="0" data-credit-value="0" data-id-product="4947">
|
||||
<a href='auction.php?a=Frullatore_85559720' class="name " title="">Frullatore Pro</a>
|
||||
</div>
|
||||
""";
|
||||
|
||||
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": ["<div id=\"divAsta1\" data-id=\"1\" data-freq=\"99\" data-id-product=\"7\"></div>"],
|
||||
"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("<div class=\"btn-rapid buy-rapid-now\">14,00 €</div>", 14.00)]
|
||||
[InlineData("<div class=\"buy-rapid-now\"><i class=\"fas fa-cart\"></i> 65,90 €</div>", 65.90)]
|
||||
[InlineData("<div class=\"buy-rapid-now\">200,00 €</div>", 200.00)]
|
||||
[InlineData("<div class=\"buy-rapid-now\">1.234,00 €</div>", 1234.00)]
|
||||
[InlineData("<div class=\"buy-rapid-now\">80 €</div>", 80)]
|
||||
public void Legge_il_prezzo_del_compra_subito(string markup, double expected)
|
||||
{
|
||||
var a = Assert.Single(CatalogPageParser.ParseAuctions($"<div id=\"divAsta9\" data-id=\"9\">{markup}</div>"));
|
||||
Assert.Equal((decimal)expected, a.BuyNowPrice);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Senza_compra_subito_il_prezzo_resta_ignoto()
|
||||
{
|
||||
Assert.Null(Assert.Single(CatalogPageParser.ParseAuctions("<div id=\"divAsta9\" data-id=\"9\">nessun riquadro</div>")).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("<html>Manutenzione in corso</html>")]
|
||||
[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": ["<div id=\"divAsta1\" data-id=\"1\"></div>"]}""")!;
|
||||
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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user