using System.Diagnostics; using System.Globalization; using BidooBidBot.Net; namespace BidooBidBot.Bidoo; /// Esito di un'interrogazione di data.php. public sealed record PollResult(AuctionState? State, HttpOutcome Outcome, string? Error); /// Esito di una puntata. public sealed record BidAttempt( bool Success, BidResponse Response, int LatencyMs, string? Error, long SentTicks, bool UsedFallback, string RawBody); /// /// Le chiamate a Bidoo (specifica §5): polling, puntata, dati del conto, pagina dell'asta. /// Gli indirizzi vengono tutti dai riferimenti. Una risposta 403 o la pagina di login al /// posto dei dati significano sessione non valida: lo si dice con . /// public sealed class BidooApi { private readonly BidooTransport _transport; private readonly BidLane _lane; private readonly Func _refs; public BidooApi(BidooTransport transport, BidLane lane, Func refs) { _transport = transport; _lane = lane; _refs = refs; } public BidooTransport Transport => _transport; public BidLane Lane => _lane; public BidooReferences References => _refs(); /// L'utente collegato, per riconoscere le proprie puntate. public string? Username { get; set; } /// La sessione non vale più (403 o pagina di login). Il testo dice cosa si è visto. public event Action? SessionInvalid; private bool CheckSession(HttpOutcome outcome) { if (!_transport.HasCookie) return true; if (outcome.StatusCode == 403) { SessionInvalid?.Invoke("Bidoo risponde 403 (accesso negato)"); return false; } if (outcome.Success && DataResponseParser.LooksLikeLoginPage(outcome.Body, _refs())) { SessionInvalid?.Invoke("Bidoo risponde con la pagina di login"); return false; } return true; } private string Referer(string auctionId, string? auctionUrl) => !string.IsNullOrEmpty(auctionUrl) ? auctionUrl! : _refs().AuctionPageUrl(auctionId); /// Una interrogazione di data.php per un'asta. public async Task PollAsync(string auctionId, string? auctionUrl, int maxHistory, CancellationToken ct, RequestPriority priority = RequestPriority.Normal) { var refs = _refs(); var url = refs.Url(refs.Endpoints.AuctionData, ("id", auctionId)); var outcome = await _transport.SendAsync(_transport.BuildGet(url, Referer(auctionId, auctionUrl)), priority, ct).ConfigureAwait(false); if (!outcome.Success) { CheckSession(outcome); return new PollResult(null, outcome, outcome.Describe()); } if (!CheckSession(outcome)) return new PollResult(null, outcome, "sessione non valida"); var parsed = DataResponseParser.Parse(auctionId, outcome.Body, outcome.LatencyMs, outcome.ReceivedTicks, Username, maxHistory, refs); return new PollResult(parsed.State, outcome, parsed.Error); } /// /// La puntata: prima sulla corsia dedicata; se questa fallisce per un errore di rete e /// mancano ancora più di ms, una sola volta sul pool /// normale (priorità critica). Un «no» di Bidoo non si ritenta mai. /// public async Task PlaceBidAsync(string auctionId, string? auctionUrl, Func? msLeft, double retryIfMsLeft, CancellationToken ct) { var refs = _refs(); var url = refs.Url(refs.Endpoints.Bid, ("id", auctionId)); var referer = Referer(auctionId, auctionUrl); var outcome = await _lane.SendBidAsync(url, referer, ct).ConfigureAwait(false); var fallback = false; if (outcome.IsNetworkError && msLeft != null && msLeft() > retryIfMsLeft) { fallback = true; var request = _transport.BuildGet(url, referer); request.Headers.TryAddWithoutValidation("Origin", refs.BaseUrl); outcome = await _transport.SendAsync(request, RequestPriority.Critical, ct).ConfigureAwait(false); } CheckSession(outcome); var parsed = DataResponseParser.ParseBidResponse(outcome.Body); string? error = null; if (!parsed.Ok) { error = outcome.Body.Length == 0 ? outcome.Describe() : parsed.Error; if (outcome.StatusCode is >= 400) error = $"HTTP {outcome.StatusCode}: {error}"; } return new BidAttempt(parsed.Ok, parsed, outcome.LatencyMs, error, outcome.SentTicks, fallback, outcome.Body); } /// buy_bids.php: utente, saldo, credito. Null se la sessione non vale. public async Task GetUserInfoAsync(CancellationToken ct) { var refs = _refs(); var outcome = await _transport.SendAsync( _transport.BuildGet(refs.Url(refs.Endpoints.UserInfo), refs.BaseUrl + "/", ajax: false), RequestPriority.Background, ct).ConfigureAwait(false); if (!outcome.Success) { CheckSession(outcome); return null; } var info = AccountParser.ParseUserPage(outcome.Body, refs); if (info?.Username == null && _transport.HasCookie && DataResponseParser.LooksLikeLoginPage(outcome.Body, refs)) { SessionInvalid?.Invoke("la pagina del conto chiede di accedere"); return null; } return info; } /// update_credits_status.php: il saldo leggero. public async Task GetCreditsAsync(CancellationToken ct) { var refs = _refs(); var outcome = await _transport.SendAsync( _transport.BuildGet(refs.Url(refs.Endpoints.CreditsStatus)), RequestPriority.Background, ct).ConfigureAwait(false); if (!outcome.Success || !CheckSession(outcome)) return null; return AccountParser.ParseCreditsStatus(outcome.Body, refs); } /// /// Aste vinte da confermare. Null = non lo so: chi chiama deve distinguere «zero» da «non /// lo so», altrimenti un errore di rete cancellerebbe dalla barra una vincita che esiste. /// È lo stesso indirizzo che il sito interroga per il pallino rosso in testata /// (UserNotifications.updateAuctionsWon in checkN_it.js) e risponde con un solo /// numero; senza sessione torna la pagina di login e il numero non si legge. /// Riferimento dalla versione desktop, non usato: GET /ajax/get_auction_bids_info_banner.php /// (JSON, con la sessione) conta le aste di puntate vinte nella giornata ai fini del /// bonus e resta a zero anche con vincite da confermare, quindi non sostituisce questa. Campi: /// nAsteConfermate, limiteAsteVinte, nAsteVinte, nPuntateRiscattate, nPuntateBonus, /// nPuntateDaRiscattare, nAstePerBonus, validUntil (unix), percentualeBonus, viewSlot, /// extraSlots (lista). Servirebbe a mostrare il programma bonus del giorno e le puntate da /// riscattare. /// public async Task GetAuctionsWonAsync(CancellationToken ct) { var refs = _refs(); var outcome = await _transport.SendAsync( _transport.BuildGet(refs.Url(refs.Endpoints.AuctionsWon)), RequestPriority.Background, ct).ConfigureAwait(false); return outcome.Success ? AccountParser.ParseAuctionsWon(outcome.Body) : null; } /// La pagina dell'asta: nome, Compralo Ora, spedizione, limite di vincita, foto. public async Task GetAuctionPageAsync(string auctionId, string? auctionUrl, CancellationToken ct) { var refs = _refs(); var url = !string.IsNullOrEmpty(auctionUrl) && auctionUrl!.StartsWith(refs.BaseUrl, StringComparison.OrdinalIgnoreCase) ? auctionUrl : refs.AuctionPageUrl(auctionId); var outcome = await _transport.SendAsync(_transport.BuildGet(url, refs.BaseUrl + "/", ajax: false), RequestPriority.Background, ct).ConfigureAwait(false); return outcome.Success ? AuctionPageParser.Parse(outcome.Body, refs) : null; } /// Stati di molte aste in una richiesta (data.php?LISTID=…). public async Task> GetListAsync(IReadOnlyList auctionIds, CancellationToken ct) { var refs = _refs(); var result = new List(); foreach (var chunk in auctionIds.Chunk(Math.Max(1, refs.Limits.BulkPricesChunk))) { var url = refs.Url(refs.Endpoints.BulkPrices, ("ids", string.Join(',', chunk)), ("unixMs", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture))); var outcome = await _transport.SendAsync(_transport.BuildGet(url), RequestPriority.Background, ct).ConfigureAwait(false); if (outcome.Success) result.AddRange(DataResponseParser.ParseList(outcome.Body, refs)); } return result; } /// Millisecondi trascorsi da un tick di Stopwatch. public static double MsSince(long ticks) => (Stopwatch.GetTimestamp() - ticks) * 1000.0 / Stopwatch.Frequency; }