diff --git a/Mimante/src/BidooBidBot/Host/BotWorld.cs b/Mimante/src/BidooBidBot/Host/BotWorld.cs
index 72c0ddd..c9390f5 100644
--- a/Mimante/src/BidooBidBot/Host/BotWorld.cs
+++ b/Mimante/src/BidooBidBot/Host/BotWorld.cs
@@ -170,6 +170,7 @@ public sealed class BotWorld : IAsyncDisposable
_jobs.Add(Checker.RunAsync(ct));
}
_jobs.Add(Watcher.RunAsync(ct));
+ if (!IsSimulator) _jobs.Add(BackfillLoopAsync(bot, ct));
bot.Log.Info("AVVIO", IsSimulator
? "Stai vedendo il simulatore: nessuna sessione Bidoo salvata. Apri «Accesso a Bidoo» per collegarti al sito vero"
: $"Sito vero: sessione di {Account.Username ?? "utente da verificare"} ({Account.SessionSource}), {Monitor.Auctions.Count} aste in elenco");
@@ -189,6 +190,25 @@ public sealed class BotWorld : IAsyncDisposable
}
}
+ /// Di fondo: ogni 6 ore (la prima dopo 10 minuti) le puntate dei vincitori mancanti.
+ private Task BackfillLoopAsync(Bot bot, CancellationToken ct) => Task.Run(async () =>
+ {
+ try { await Task.Delay(TimeSpan.FromMinutes(10), ct).ConfigureAwait(false); }
+ catch (OperationCanceledException) { return; }
+ while (!ct.IsCancellationRequested)
+ {
+ try
+ {
+ await new WinnerBidsBackfill(Api, bot.Db, bot.Queue, bot.Log, Name)
+ .RunAsync(200, null, bot.Settings.Current.TransactionFeeEuro, ct).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) { return; }
+ catch (Exception ex) { bot.Log.Warn("PRODOTTI", $"Recupero delle puntate dei vincitori non riuscito: {ex.Message}"); }
+ try { await Task.Delay(TimeSpan.FromHours(6), ct).ConfigureAwait(false); }
+ catch (OperationCanceledException) { return; }
+ }
+ }, ct);
+
private readonly SemaphoreSlim _topUp = new(1, 1);
private async Task TopUpSimulatorAsync(CancellationToken ct)
diff --git a/Mimante/src/BidooBidBot/Products/WinnerBidsBackfill.cs b/Mimante/src/BidooBidBot/Products/WinnerBidsBackfill.cs
new file mode 100644
index 0000000..f97c20f
--- /dev/null
+++ b/Mimante/src/BidooBidBot/Products/WinnerBidsBackfill.cs
@@ -0,0 +1,103 @@
+using BidooBidBot.Bidoo;
+using BidooBidBot.Data;
+using BidooBidBot.Logging;
+using BidooBidBot.Ml;
+
+namespace BidooBidBot.Products;
+
+///
+/// Il recupero delle puntate dei vincitori (portato da WinnerBidsBackfill): per le aste
+/// chiuse che non le hanno (la lettura finale mancata, un riavvio a cavallo della fine) si
+/// richiede data.php dell'asta conclusa, che le dichiara ancora. Un dato incoerente con
+/// il prezzo finale si scarta invece di spostare le medie. Una richiesta ogni 250 ms, in
+/// priorità di fondo: non ruba nulla al motore.
+///
+public sealed class WinnerBidsBackfill
+{
+ private const int DelayBetweenRequestsMs = 250;
+
+ private readonly BidooApi _api;
+ private readonly Db _db;
+ private readonly WriteQueue _queue;
+ private readonly AppLog _log;
+ private readonly string _world;
+
+ public WinnerBidsBackfill(BidooApi api, Db db, WriteQueue queue, AppLog log, string world)
+ {
+ _api = api;
+ _db = db;
+ _queue = queue;
+ _log = log;
+ _world = world;
+ }
+
+ public sealed record Result(int Examined, int Updated, int Failed, int Skipped);
+
+ public Task> FindMissingAsync(int max) =>
+ _db.QueryAsync(
+ "SELECT auction_id, name, product_key, final_price FROM auctions WHERE type = $1 AND outcome IS NOT NULL AND final_price IS NOT NULL " +
+ "AND winner_bids_paid IS NULL AND winner_bids_free IS NULL AND COALESCE(winner_user, '') <> '' ORDER BY end_time DESC LIMIT $2",
+ r => (r.Str("auction_id"), r.Str("name"), r.Str("product_key"), r.Dbl("final_price")), _world, max <= 0 ? 100_000 : max);
+
+ public async Task RunAsync(int max, IProgress? progress, double transactionFee, CancellationToken ct)
+ {
+ var missing = await FindMissingAsync(max).ConfigureAwait(false);
+ int updated = 0, failed = 0, skipped = 0;
+ var touched = new HashSet(StringComparer.Ordinal);
+
+ for (var i = 0; i < missing.Count; i++)
+ {
+ if (ct.IsCancellationRequested) break;
+ var (id, name, key, final) = missing[i];
+ try
+ {
+ var poll = await _api.PollAsync(id, null, 1, ct).ConfigureAwait(false);
+ var s = poll.State;
+ if (s?.WinnerBidsTotal is not { } total || !s.IsTerminal)
+ {
+ skipped++;
+ }
+ else if (AuctionIntegrity.Trusted(final, total) is null)
+ {
+ skipped++;
+ _log.Info("PRODOTTI", $"Puntate del vincitore di '{name}' scartate: {total} non torna con il prezzo finale");
+ }
+ else
+ {
+ _queue.Enqueue("UPDATE auctions SET winner_bids_paid = $2, winner_bids_free = $3 WHERE auction_id = $1",
+ id, s.WinnerBidsPaid, s.WinnerBidsFree);
+ if (!string.IsNullOrEmpty(key)) touched.Add(key);
+ updated++;
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ break;
+ }
+ catch (Exception ex)
+ {
+ failed++;
+ _log.Debug("PRODOTTI", $"Recupero {id}: {ex.Message}");
+ }
+
+ progress?.Report(new ProgressStep(i + 1, missing.Count, $"{updated} recuperate"));
+ try { await Task.Delay(DelayBetweenRequestsMs, ct).ConfigureAwait(false); }
+ catch (OperationCanceledException) { break; }
+ }
+
+ if (touched.Count > 0 && _world == Worlds.Real)
+ {
+ await _queue.FlushAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
+ foreach (var key in touched)
+ {
+ try { await ProductStatsRepository.RefreshAsync(_db, _queue, key, transactionFee).ConfigureAwait(false); }
+ catch (Exception ex) { _log.Debug("PRODOTTI", $"Statistiche di {key}: {ex.Message}"); }
+ }
+ }
+
+ if (missing.Count > 0)
+ _log.Info("PRODOTTI", $"Recupero delle puntate dei vincitori: {updated} aste aggiornate su {missing.Count} esaminate" +
+ (skipped > 0 ? $", {skipped} senza dato utilizzabile" : "") + (failed > 0 ? $", {failed} errori" : ""));
+ return new Result(missing.Count, updated, failed, skipped);
+ }
+}
diff --git a/Mimante/src/BidooBidBot/Session/Cdp/AssistedLogin.cs b/Mimante/src/BidooBidBot/Session/Cdp/AssistedLogin.cs
index f9368dc..c86608e 100644
--- a/Mimante/src/BidooBidBot/Session/Cdp/AssistedLogin.cs
+++ b/Mimante/src/BidooBidBot/Session/Cdp/AssistedLogin.cs
@@ -40,6 +40,7 @@ public sealed class AssistedLogin : IAsyncDisposable
private CancellationTokenSource? _watch;
private long _lastInput;
private volatile bool _done;
+ private TaskCompletionSource? _loaded;
public AssistedLogin(string profileDir, Func refs, AppLog log)
{
@@ -94,8 +95,14 @@ public sealed class AssistedLogin : IAsyncDisposable
if (_userAgent != null)
await _cdp.SendAsync("Network.setUserAgentOverride", new { userAgent = _userAgent, acceptLanguage = "it-IT,it;q=0.9,en;q=0.7" }, _session, ct).ConfigureAwait(false);
await _cdp.SendAsync("Emulation.setDeviceMetricsOverride", new { width = 1280, height = 900, deviceScaleFactor = 1, mobile = false }, _session, ct).ConfigureAwait(false);
+ _loaded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await _cdp.SendAsync("Page.navigate", new { url = refs.Url(refs.Endpoints.Login) }, _session, ct).ConfigureAwait(false);
- await _cdp.SendAsync("Page.startScreencast", new { format = "jpeg", quality = 60, maxWidth = 1280, maxHeight = 900, everyNthFrame = 1 }, _session, ct).ConfigureAwait(false);
+
+ // Da about:blank a Bidoo la pagina cambia processo: lo screencast parte a caricamento
+ // finito, con qualche ritentativo («Not attached to an active page» nel frattempo).
+ try { await _loaded.Task.WaitAsync(TimeSpan.FromSeconds(15), ct).ConfigureAwait(false); }
+ catch (TimeoutException) { /* pagina lenta: si prova lo stesso */ }
+ await StartScreencastAsync(ct).ConfigureAwait(false);
_lastInput = Environment.TickCount64;
_watch = new CancellationTokenSource();
@@ -118,10 +125,29 @@ public sealed class AssistedLogin : IAsyncDisposable
}
}
+ private async Task StartScreencastAsync(CancellationToken ct)
+ {
+ for (var attempt = 1; ; attempt++)
+ {
+ try
+ {
+ await _cdp!.SendAsync("Page.startScreencast", new { format = "jpeg", quality = 60, maxWidth = 1280, maxHeight = 900, everyNthFrame = 1 }, _session, ct).ConfigureAwait(false);
+ return;
+ }
+ catch (CdpException) when (attempt < 10)
+ {
+ await Task.Delay(500, ct).ConfigureAwait(false);
+ }
+ }
+ }
+
private void OnEvent(string method, JsonElement p, string? session)
{
switch (method)
{
+ case "Page.loadEventFired":
+ _loaded?.TrySetResult();
+ break;
case "Page.screencastFrame":
var frameSession = p.GetProperty("sessionId").GetInt32();
_cdp?.Post("Page.screencastFrameAck", new { sessionId = frameSession }, _session);
@@ -152,7 +178,7 @@ public sealed class AssistedLogin : IAsyncDisposable
try
{
var refs = _refs();
- if (_url.Length == 0 || refs.Recognizers.LoginPageMarkers.Any(m => _url.Contains(m, StringComparison.OrdinalIgnoreCase))) continue;
+ if (IsLoginUrl(_url, refs)) continue;
if (!_url.StartsWith(refs.BaseUrl, StringComparison.OrdinalIgnoreCase)) continue;
var result = await _cdp!.SendAsync("Network.getCookies", new { urls = new[] { refs.BaseUrl + "/" } }, _session, ct).ConfigureAwait(false);
@@ -174,6 +200,15 @@ public sealed class AssistedLogin : IAsyncDisposable
}
}
+ ///
+ /// Siamo ancora sul login? Oltre ai segni dei riferimenti, Bidoo apre il login anche come
+ /// finestra sulla home (/?login=true&redirect=…).
+ ///
+ internal static bool IsLoginUrl(string url, BidooReferences refs) =>
+ url.Length == 0 ||
+ refs.Recognizers.LoginPageMarkers.Any(m => url.Contains(m, StringComparison.OrdinalIgnoreCase)) ||
+ url.Contains("login=true", StringComparison.OrdinalIgnoreCase);
+
public async Task InputAsync(LoginInput input, CancellationToken ct)
{
var cdp = _cdp;
diff --git a/Mimante/src/BidooBidBot/Web/WebSocketHub.Commands.cs b/Mimante/src/BidooBidBot/Web/WebSocketHub.Commands.cs
index 04c3d8f..586e3da 100644
--- a/Mimante/src/BidooBidBot/Web/WebSocketHub.Commands.cs
+++ b/Mimante/src/BidooBidBot/Web/WebSocketHub.Commands.cs
@@ -230,6 +230,18 @@ public sealed partial class WebSocketHub
var n = await Api.ApplySuggestedAsync(_bot, ct).ConfigureAwait(false);
return new Ack(true, $"Limiti consigliati applicati a {n} prodotti");
}
+ case "products.backfill_winners":
+ {
+ var progress = new Progress(p => c.Send(Serialize(new Dictionary
+ {
+ ["t"] = "progress", ["op"] = "backfill", ["done"] = p.Done, ["total"] = p.Total, ["detail"] = p.Detail
+ })));
+ var backfill = new WinnerBidsBackfill(world.Api, _bot.Db, _bot.Queue, _bot.Log, world.Name);
+ var r = await backfill.RunAsync(Int(m, "max") ?? 0, progress, _bot.Settings.Current.TransactionFeeEuro, ct).ConfigureAwait(false);
+ return new Ack(true, r.Examined == 0
+ ? "Nessuna asta chiusa senza le puntate del vincitore"
+ : $"{r.Updated} aste aggiornate su {r.Examined}" + (r.Skipped > 0 ? $", {r.Skipped} senza dato utilizzabile" : ""));
+ }
case "products.refresh_stats":
{
var n = 0;
diff --git a/Mimante/src/BidooBidBot/wwwroot/js/pages/prodotti.js b/Mimante/src/BidooBidBot/wwwroot/js/pages/prodotti.js
index 417cce5..58298f5 100644
--- a/Mimante/src/BidooBidBot/wwwroot/js/pages/prodotti.js
+++ b/Mimante/src/BidooBidBot/wwwroot/js/pages/prodotti.js
@@ -14,6 +14,7 @@ export async function mount(root) {
root.append(el('div', { class: 'toolbar' },
el('h1', null, 'Prodotti'), counts, search, el('span', { class: 'spacer' }),
el('button', { class: 'btn', type: 'button', onclick: applySuggested, title: 'Scrive i limiti consigliati su tutte le schede che cambiano (dice prima quante sono). Sono consigli: il modello resta l\'unico decisore' }, 'Usa consigliati su tutti'),
+ el('button', { class: 'btn', type: 'button', onclick: backfill, title: 'Chiede a Bidoo le puntate dei vincitori delle aste chiuse che non le hanno (una ogni 250 ms, in sottofondo al motore); succede da sé ogni 6 ore' }, 'Recupera puntate dei vincitori'),
el('button', { class: 'btn', type: 'button', onclick: refreshStats, title: 'Ricalcola le statistiche di tutti i prodotti dalle aste concluse (anche le puntate dei vincitori coerenti col prezzo)' }, 'Ricalcola statistiche'),
el('button', { class: 'btn', type: 'button', onclick: exportCsv, title: 'Esporta schede e statistiche in prodotti-.csv, con legenda' }, 'Esporta CSV')));
@@ -79,6 +80,14 @@ async function applySuggested() {
await load();
}
+async function backfill() {
+ const stop = subscribe('progress', m => { if (m.op === 'backfill') counts.textContent = `Recupero puntate dei vincitori: ${num(m.done)} su ${num(m.total)} (${m.detail || ''})`; });
+ const ack = await send({ t: 'products.backfill_winners' }, 60 * 60 * 1000);
+ stop();
+ report(ack);
+ await load();
+}
+
async function refreshStats() {
report(await send({ t: 'products.refresh_stats' }, 120000));
await load();
diff --git a/Mimante/tests/BidooBidBot.Tests/ServiceTests.cs b/Mimante/tests/BidooBidBot.Tests/ServiceTests.cs
index 7082a24..724bf3d 100644
--- a/Mimante/tests/BidooBidBot.Tests/ServiceTests.cs
+++ b/Mimante/tests/BidooBidBot.Tests/ServiceTests.cs
@@ -150,6 +150,16 @@ public class CdpClientTests
Assert.True(cdp.IsClosed);
}
+ [Fact]
+ public void Il_login_si_riconosce_anche_come_finestra_sulla_home()
+ {
+ var refs = BidooReferences.Default;
+ Assert.True(AssistedLogin.IsLoginUrl("https://it.bidoo.com/login.php", refs));
+ Assert.True(AssistedLogin.IsLoginUrl("https://it.bidoo.com/?login=true&redirect=index.php", refs));
+ Assert.True(AssistedLogin.IsLoginUrl("", refs));
+ Assert.False(AssistedLogin.IsLoginUrl("https://it.bidoo.com/index.php", refs));
+ }
+
[Fact]
public void DevToolsActivePort_da_l_indirizzo_del_browser()
{
diff --git a/Mimante/tools/Screenshots/Program.cs b/Mimante/tools/Screenshots/Program.cs
index 85403f6..c156993 100644
--- a/Mimante/tools/Screenshots/Program.cs
+++ b/Mimante/tools/Screenshots/Program.cs
@@ -97,6 +97,22 @@ const string clickFirst = "document.querySelector('.split tbody tr[data-id]')?.c
await Shot("01-aste", "#/aste", clickFirst, 4000);
await Shot("02-apprendimento", "#/apprendimento", null, 3500);
await Shot("03-accesso-bidoo", "#/accesso");
+if (args.Contains("--accesso-assistito"))
+{
+ // Apre il browser del bot (Chromium dentro il bot) e aspetta il primo fotogramma.
+ await Eval("document.querySelector('.browser .idle button')?.click()");
+ var frame = false;
+ for (var i = 0; i < 40 && !frame; i++)
+ {
+ await Task.Delay(500, ct);
+ frame = (await Eval("!document.querySelector('.browser canvas').hidden")).ValueKind == JsonValueKind.True;
+ }
+ await Task.Delay(2500, ct);
+ await Shot("03-accesso-bidoo", "#/accesso", null, 200);
+ Console.WriteLine(frame ? "Browser del bot: fotogrammi ricevuti" : "Browser del bot: nessun fotogramma");
+ if (!frame) errors.Add("accesso assistito: nessun fotogramma dal browser del bot");
+ await Eval("document.querySelector('.browser .url button[title^=\"Chiudi\"]')?.click()");
+}
await Shot("04-prodotti", "#/prodotti", clickFirst);
await Shot("05-impostazioni", "#/impostazioni");
await Shot("06-storico", "#/storico", clickFirst);