Il servizio stava in Mimante/ con, alla radice, il README e il .gitignore della vecchia app WPF. Come negli altri progetti (Febe), soluzione, sorgenti, documenti e Docker stanno ora alla radice. Solo spostamenti con git mv, così la storia di ogni file si segue con --follow; nessun contenuto cambia. Tolti: il README della app WPF (quello del bot prende il suo posto), Modifiche.txt (vuoto) e i due flussi di .gitea/workflows, che non sono mai partiti e pubblicavano la porta 5432 sul Docker dove gira il PostgreSQL vero: li sostituisce la CI nuova. Fino ad allora nessun flusso parte. .gitignore unico, preso da Febe, con le voci del bot più /dati/ (i dati scaricati per l'analisi) e .claude/worktrees/. Build e 288 test verdi dalla radice (14 sul database saltati senza TEST_DB_HOST). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
205 lines
9.3 KiB
C#
205 lines
9.3 KiB
C#
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: chi chiama deve distinguere «zero» da «non
|
|
/// lo so», altrimenti un errore di rete cancellerebbe dalla barra una vincita che esiste.
|
|
/// <para>È lo stesso indirizzo che il sito interroga per il pallino rosso in testata
|
|
/// (<c>UserNotifications.updateAuctionsWon</c> in <c>checkN_it.js</c>) e risponde con un solo
|
|
/// numero; senza sessione torna la pagina di login e il numero non si legge.</para>
|
|
/// <para>Riferimento dalla versione desktop, non usato: <c>GET /ajax/get_auction_bids_info_banner.php</c>
|
|
/// (JSON, con la sessione) conta le aste <i>di puntate</i> vinte nella giornata ai fini del
|
|
/// bonus e resta a zero anche con vincite da confermare, quindi non sostituisce questa. Campi:
|
|
/// <c>nAsteConfermate, limiteAsteVinte, nAsteVinte, nPuntateRiscattate, nPuntateBonus,
|
|
/// nPuntateDaRiscattare, nAstePerBonus, validUntil</c> (unix), <c>percentualeBonus, viewSlot,
|
|
/// extraSlots</c> (lista). Servirebbe a mostrare il programma bonus del giorno e le puntate da
|
|
/// riscattare.</para>
|
|
/// </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;
|
|
}
|