From 6cbc5e58b0a4f5488999f685700214fe32e0812c Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 24 Nov 2026 18:48:05 +0100 Subject: [PATCH] Ricompense di Bidoo e campanella come seconda fonte del riscatto (#38) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Il bot riscattava i collegamenti di puntateaste.it ma non sapeva se Bidoo li avesse accreditati davvero, e perdeva i collegamenti che arrivano solo nella campanella del sito. - A intervalli (FreeBidsRewardsHours, 6 ore, 0 = mai) legge /my_chests.php e la prima pagina di /bids_history.php, salva le ricompense nuove in account_rewards (migrazione 0006, chiave unica, solo inserimenti) e scrive nel registro se i conti del giorno con i riscatti del bot tornano. - La campanella /checkN.php diventa seconda fonte (FreeBidsUseNotifications): solo la lettura semplice, mai _d o _r, cosi' le notifiche restano non lette. - Pagina Puntate gratis: scheda «Ricompense di Bidoo» e ora dell'ultima lettura. - La tabella entra nello scaricamento dei dati; test con copie della struttura vera delle due pagine e della campanella, valori inventati. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +- .../0015-riscatto-delle-puntate-gratuite.md | 6 +- docs/architettura.md | 9 + docs/stato.md | 4 +- src/Mimante/Bidoo/BidooApi.FreeBids.cs | 28 +++ src/Mimante/Bidoo/BidooReferences.cs | 2 + src/Mimante/Bidoo/FreeBids/FreeBidsService.cs | 95 ++++++++- src/Mimante/Bidoo/FreeBids/RewardsPages.cs | 194 ++++++++++++++++++ src/Mimante/Bidoo/bidoo.default.json | 6 +- src/Mimante/Data/Archive/ArchiveTables.cs | 2 + .../Data/Migrations/0006_ricompense.sql | 18 ++ src/Mimante/Host/BotWorld.cs | 1 + src/Mimante/Settings/AppSettings.cs | 6 + src/Mimante/Settings/SettingsStore.cs | 1 + src/Mimante/Web/Api.cs | 9 + src/Mimante/Web/Views.cs | 2 + src/Mimante/wwwroot/js/pages/impostazioni.js | 2 + .../wwwroot/js/pages/puntate-gratis.js | 21 +- tests/Mimante.Tests/Fixtures/campanella.json | 1 + .../Fixtures/cronologia-crediti.html | 42 ++++ .../Fixtures/ricompense-forzieri.html | 49 +++++ tests/Mimante.Tests/RewardsPagesTests.cs | 99 +++++++++ 22 files changed, 590 insertions(+), 12 deletions(-) create mode 100644 src/Mimante/Bidoo/FreeBids/RewardsPages.cs create mode 100644 src/Mimante/Data/Migrations/0006_ricompense.sql create mode 100644 tests/Mimante.Tests/Fixtures/campanella.json create mode 100644 tests/Mimante.Tests/Fixtures/cronologia-crediti.html create mode 100644 tests/Mimante.Tests/Fixtures/ricompense-forzieri.html create mode 100644 tests/Mimante.Tests/RewardsPagesTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index e3d48f1..8f8447d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,7 +37,10 @@ copia nella release la sezione della versione. riscattate, dei forzieri visti e il registro delle operazioni. Spento di fabbrica; uno alla volta finché il primo accredito non si vede nel saldo, tetti per giro e per giorno, solo nelle ore scelte, pausa da sola se Bidoo chiede una verifica. Si può anche incollare un collegamento e riscattarlo subito. I - forzieri si segnalano su Telegram, non si aprono. + forzieri si segnalano su Telegram, non si aprono. I collegamenti arrivano anche dalla campanella di + Bidoo, letta senza segnare le notifiche come lette; a intervalli il bot legge le ricompense e la + cronologia crediti di Bidoo (scheda «Ricompense di Bidoo», migrazione 0006) e scrive nel registro se i + conti con i suoi riscatti tornano. - **Grafica nuova, sulla linea di Febe** (ADR 0016): grigio caldo, carte bianche, accento blu petrolio, carattere Archivo, righe più ariose. La barra laterale tiene in fondo il mondo (sito vero o simulatore) e l'utente Bidoo; elenco e pannello stanno in due riquadri. Il tema di fabbrica segue quello del sistema: diff --git a/docs/adr/0015-riscatto-delle-puntate-gratuite.md b/docs/adr/0015-riscatto-delle-puntate-gratuite.md index 88281aa..3375921 100644 --- a/docs/adr/0015-riscatto-delle-puntate-gratuite.md +++ b/docs/adr/0015-riscatto-delle-puntate-gratuite.md @@ -47,8 +47,8 @@ server. I forzieri si vedono con `get_chest_tag_url.php?tag=N` per categoria. ## Conseguenze - Il riscatto si scosta da §4.3 della specifica (`docs/stato.md`, «Deviazioni»). -- Rimandati alla issue «Ricompense e seconda fonte del riscatto»: la lettura di `/my_chests.php` e - `/bids_history.php` (tabella delle ricompense ottenute e confronto con gli accrediti) e la campanella - `/checkN.php` come seconda fonte di collegamenti. +- Fatti nella issue #38 «Ricompense e seconda fonte del riscatto»: la lettura di `/my_chests.php` e + `/bids_history.php` (tabella `account_rewards`, migrazione 0006, e confronto con i riscatti) e la + campanella `/checkN.php` come seconda fonte di collegamenti, letta senza segnare le notifiche. - Il primo riscatto dal bot va fatto dal vivo, con Alberto, e la risposta registrata va confrontata con il saldo prima di lasciarlo acceso. diff --git a/docs/architettura.md b/docs/architettura.md index f94c866..f266747 100644 --- a/docs/architettura.md +++ b/docs/architettura.md @@ -291,6 +291,7 @@ un secondo pool con tempo massimo di 15 s. | `product_stats` | Statistiche per prodotto ricalcolate a ogni chiusura (JSON, campi nuovi annullabili): la pagina Prodotti non rilegge lo storico, e i paletti calcolati ne derivano. | | `promo_redemptions` | Ogni tentativo di riscatto di un codice gratuito (migrazione 0005) con esito, saldo prima e dopo, stato della pagina e risposta grezza: serve allo storico per i contatori della pagina Puntate gratis e per non riaprire un codice già usato, scaduto o tentato troppe volte. | | `chests` | I forzieri visti, una riga per categoria, indirizzo e giorno con la prima e l'ultima volta: serve allo storico per la scheda Forzieri e per avvisare una volta sola. | +| `account_rewards` | Le ricompense che Bidoo ha accreditato davvero, lette dalle sue pagine (forzieri aperti da `/my_chests.php`, movimenti di `/bids_history.php`; migrazione 0006), una riga per ricompensa con una chiave unica: serve allo storico per confrontare i riscatti del bot con ciò che Bidoo segna e per la scheda «Ricompense di Bidoo». | `bids`, `resets` e `bot_decisions` sono partizionate per mese su `created_at`; la partizione del mese dopo nasce il giorno 25 e all'avvio. @@ -342,8 +343,16 @@ Lo strumento da riga di comando legge l'archivio su una connessione propria in s risposta da `PromoResponse` e il risultato va in tabella, nel registro e, se serve, su Telegram. Gli esiti che chiedono attenzione mettono in pausa il servizio (documento `freebids/state`) finché non la si toglie dalla pagina. + Seconda fonte (`FreeBidsUseNotifications`, acceso): la campanella `freeBids.notifications` + (`/checkN.php` senza parametri, come la legge il sito quando si apre il riquadro); `RewardsPages` + tiene gli indirizzi con `promocode` e passano dallo stesso controllo. Il bot non manda mai `_d=1` né + `_r=1`, le due richieste con cui il sito segna le notifiche come consegnate o lette. - **Forzieri** (`RunChestsAsync`, spento di fabbrica): ogni `ChestWatchMinutes` prova le categorie di `freeBids.chestTags`; un forziere nuovo va in `chests` e su Telegram una volta al giorno. +- **Ricompense** (`RunRewardsAsync`, ogni `FreeBidsRewardsHours` ore, 0 = mai): legge `/my_chests.php` e la + prima pagina di `/bids_history.php` (`RewardsPages`: data italiana dei forzieri, ora dei movimenti dallo + script della pagina), salva le nuove in `account_rewards` e scrive nel registro il confronto del giorno + fra le ricompense «tramite link» e i riscatti riusciti del bot. L'interfaccia riceve il blocco `freebids` (stato, pausa, ultimo e prossimo giro, ultime righe del registro) e legge contatori e tabelle da `GET /api/puntate-gratis`; i comandi sono `freebids.run`, diff --git a/docs/stato.md b/docs/stato.md index 40ee5ea..794d808 100644 --- a/docs/stato.md +++ b/docs/stato.md @@ -249,8 +249,8 @@ cambiarle; dove serve, il punto nel codice è indicato. della decisione (con una mia puntata, chi ha risposto alla mia). - **Riscatto delle puntate gratuite** (2.0.0, ADR 0015): §4.3 lo escludeva. Su richiesta di Alberto c'è di nuovo, spento di fabbrica, con la pagina «Puntate gratis»; i forzieri si segnalano e non si aprono. - Mancano ancora la lettura delle ricompense (`/my_chests.php`, `/bids_history.php`) e la campanella come - seconda fonte, e il primo riscatto dal bot va fatto dal vivo. + Con la #38 legge anche le ricompense (`/my_chests.php`, `/bids_history.php`) e la campanella come + seconda fonte; il primo riscatto dal bot va ancora fatto dal vivo. - **Niente browser nel bot** (2.0.0, ADR 0017): §6.5, §9 e §10.2 volevano l'accesso assistito con Chromium nel container. Su richiesta di Alberto la sessione si incolla dalla pagina «Accesso a Bidoo» («Copia come cURL» di Chrome, intestazioni, riga Cookie o valore di `__stattrb`): i cookie di Bidoo diff --git a/src/Mimante/Bidoo/BidooApi.FreeBids.cs b/src/Mimante/Bidoo/BidooApi.FreeBids.cs index 6240e25..0413646 100644 --- a/src/Mimante/Bidoo/BidooApi.FreeBids.cs +++ b/src/Mimante/Bidoo/BidooApi.FreeBids.cs @@ -42,6 +42,34 @@ public sealed partial class BidooApi page.StatusCode, page.LatencyMs + answer.LatencyMs); } + /// + /// Una pagina del conto (ricompense, cronologia crediti) come documento, con la sessione: il testo, o perché + /// non si è letta. Non passa da CheckSession: una pagina di servizio che cambia non deve far risultare + /// scaduta la sessione delle puntate; ci pensa il controllo della sessione sulla pagina del conto. + /// + public async Task<(string? Body, string? Error)> GetAccountPageAsync(string path, CancellationToken ct) + { + var refs = _refs(); + var outcome = await _transport.SendAsync(_transport.BuildGet(refs.Url(path), refs.BaseUrl.TrimEnd('/') + "/", ajax: false), + RequestPriority.Background, ct, followRedirects: false).ConfigureAwait(false); + if (!outcome.Success) return (null, outcome.Describe()); + if (DataResponseParser.LooksLikeLoginPage(outcome.Body, refs)) return (null, "Bidoo risponde con la pagina di accesso"); + return (outcome.Body, null); + } + + /// + /// La campanella (/checkN.php senza parametri), come la legge il sito quando si apre il riquadro delle + /// notifiche. Solo lettura: le notifiche si segnano come consegnate o lette con _d=1 e _r=1&l=…, + /// due richieste separate che il bot non fa mai. + /// + public async Task<(string? Body, string? Error)> GetNotificationsAsync(CancellationToken ct) + { + var refs = _refs(); + var outcome = await _transport.SendAsync(_transport.BuildGet(refs.Url(refs.FreeBids.Notifications), refs.BaseUrl.TrimEnd('/') + "/"), + RequestPriority.Background, ct, followRedirects: false).ConfigureAwait(false); + return outcome.Success ? (outcome.Body, null) : (null, outcome.Describe()); + } + /// Se in una categoria c'è un forziere: {"url": null} o {"url": "…"}. Non serve la sessione. public async Task ProbeChestAsync(int tag, CancellationToken ct) { diff --git a/src/Mimante/Bidoo/BidooReferences.cs b/src/Mimante/Bidoo/BidooReferences.cs index 0a6f28f..ae8763a 100644 --- a/src/Mimante/Bidoo/BidooReferences.cs +++ b/src/Mimante/Bidoo/BidooReferences.cs @@ -39,6 +39,8 @@ public sealed class BidooReferences public string ChestTag { get; set; } = ""; public List ChestTags { get; set; } = new(); public string RewardsPage { get; set; } = ""; + public string CreditsHistoryPage { get; set; } = ""; + public string Notifications { get; set; } = ""; } /// L'host di Bidoo (da ): l'unico su cui si apre un collegamento promozionale. diff --git a/src/Mimante/Bidoo/FreeBids/FreeBidsService.cs b/src/Mimante/Bidoo/FreeBids/FreeBidsService.cs index 7097ecc..2b3c48e 100644 --- a/src/Mimante/Bidoo/FreeBids/FreeBidsService.cs +++ b/src/Mimante/Bidoo/FreeBids/FreeBidsService.cs @@ -37,7 +37,8 @@ public sealed class FreeBidsService : IDisposable /// Come sta il servizio, per l'interfaccia. public sealed record Status(bool Enabled, bool Available, string? Unavailable, bool Running, bool Paused, string? PauseReason, - bool Confirmed, DateTime? LastRunUtc, DateTime? NextRunUtc, string? LastSummary, bool ChestWatch, DateTime? LastChestUtc, int ChestsToday); + bool Confirmed, DateTime? LastRunUtc, DateTime? NextRunUtc, string? LastSummary, bool ChestWatch, DateTime? LastChestUtc, int ChestsToday, + DateTime? LastRewardsUtc = null, string? RewardsSummary = null); private readonly BidooApi _api; private readonly ExternalHttp _external; @@ -58,8 +59,8 @@ public sealed class FreeBidsService : IDisposable private readonly HashSet _chestsSeen = new(StringComparer.Ordinal); private State _state; private volatile bool _running; - private DateTime? _lastRunUtc, _nextRunUtc, _lastChestUtc; - private string? _lastSummary; + private DateTime? _lastRunUtc, _nextRunUtc, _lastChestUtc, _lastRewardsUtc; + private string? _lastSummary, _rewardsSummary; private DateOnly _chestDay; public FreeBidsService(BidooApi api, Func refs, Func settings, AccountState account, @@ -97,7 +98,7 @@ public sealed class FreeBidsService : IDisposable lock (_sync) chests = _chestsSeen.Count; return new Status(s.FreeBidsEnabled, available, available ? null : "serve l'utente di Bidoo collegato", _running, _state.Paused, _state.PauseReason, _state.Confirmed, _lastRunUtc, s.FreeBidsEnabled ? _nextRunUtc : null, _lastSummary, s.ChestWatchEnabled, - _lastChestUtc, chests); + _lastChestUtc, chests, _lastRewardsUtc, _rewardsSummary); } /// Toglie la pausa (dalla pagina): il prossimo giro riparte con un collegamento solo, finché il saldo non conferma. @@ -148,6 +149,66 @@ public sealed class FreeBidsService : IDisposable } }, ct); + /// La lettura delle ricompense, a intervalli di ore, se accesa e con l'utente collegato. + public Task RunRewardsAsync(CancellationToken ct) => Task.Run(async () => + { + if (!await DelayAsync(TimeSpan.FromMinutes(3), ct).ConfigureAwait(false)) return; + while (!ct.IsCancellationRequested) + { + var s = _settings(); + if (s.FreeBidsRewardsHours > 0 && _canRedeem()) + { + try { await SyncRewardsAsync(ct).ConfigureAwait(false); } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } + catch (Exception ex) { Note($"lettura delle ricompense non riuscita: {ex.Message}", warn: true); } + } + var hours = Math.Max(1, s.FreeBidsRewardsHours); + if (!await DelayAsync(TimeSpan.FromHours(hours) + TimeSpan.FromSeconds(_rng.Next(0, 301)), ct).ConfigureAwait(false)) return; + } + }, ct); + + /// + /// Legge le ricompense ottenute (forzieri) e la prima pagina della cronologia crediti, salva le nuove in + /// account_rewards e confronta quelle di oggi da collegamento con i riscatti riusciti del bot. + /// + public async Task SyncRewardsAsync(CancellationToken ct) + { + if (!_canRedeem()) return "nessuna lettura: serve l'utente di Bidoo collegato"; + var fb = _refs().FreeBids; + var all = new List(); + var problems = new List(); + + var (chestPage, chestError) = await _api.GetAccountPageAsync(fb.RewardsPage, ct).ConfigureAwait(false); + var chests = chestPage != null ? RewardsPages.ParseChests(chestPage, AppInfo.TimeZone) : new RewardsRead([], chestError); + if (chests.Error != null) problems.Add($"ricompense: {chests.Error}"); + all.AddRange(chests.Items); + + await Task.Delay(1000 + _rng.Next(0, 2000), ct).ConfigureAwait(false); + var (creditPage, creditError) = await _api.GetAccountPageAsync(fb.CreditsHistoryPage, ct).ConfigureAwait(false); + var credits = creditPage != null ? RewardsPages.ParseCreditHistory(creditPage) : new RewardsRead([], creditError); + if (credits.Error != null) problems.Add($"cronologia crediti: {credits.Error}"); + all.AddRange(credits.Items); + + var keys = all.Select(r => r.Key).Distinct(StringComparer.Ordinal).ToArray(); + var known = keys.Length == 0 ? new HashSet(StringComparer.Ordinal) + : (await _db.QueryAsync("SELECT key FROM account_rewards WHERE key = ANY($1)", r => r.Str("key"), keys).ConfigureAwait(false)) + .ToHashSet(StringComparer.Ordinal); + var fresh = all.Where(r => known.Add(r.Key)).ToList(); + foreach (var r in fresh) + _queue.Enqueue("INSERT INTO account_rewards(key, kind, ts, bids, free, source, description) VALUES($1, $2, $3, $4, $5, $6, $7) " + + "ON CONFLICT (key) DO NOTHING", r.Key, r.Kind, r.AtUtc, r.Bids, r.Free, r.Source, LogText.Clean(r.Description)); + + var today = DateOnly.FromDateTime(AppInfo.LocalNow); + var (redeemed, gained) = await CreditedTodayWithGainAsync(ct).ConfigureAwait(false); + var head = $"ricompense lette: {chests.Items.Count} forzieri e {credits.Items.Count} movimenti, {fresh.Count} nuovi"; + var text = chests.Error == null ? $"{head}; {RewardsPages.CompareToday(chests.Items, today, AppInfo.TimeZone, redeemed, gained)}" : head; + foreach (var p in problems) Note(p, warn: true); + _rewardsSummary = text; + _lastRewardsUtc = DateTime.UtcNow; + Note(text); + return text; + } + public static bool InHours(AppSettings s, int hour) => s.FreeBidsHoursStart == s.FreeBidsHoursEnd || (s.FreeBidsHoursStart < s.FreeBidsHoursEnd @@ -183,6 +244,20 @@ public sealed class FreeBidsService : IDisposable } } + // Seconda fonte: la campanella di Bidoo, letta senza segnare nulla. + if (_settings().FreeBidsUseNotifications) + { + var (body, error) = await _api.GetNotificationsAsync(ct).ConfigureAwait(false); + var bell = body != null ? RewardsPages.ParseNotifications(body) : new NotificationLinks(0, [], error); + if (bell.Error != null) Note($"campanella: {bell.Error}"); + foreach (var (_, href) in bell.Links) + { + var v = PromoLinkCheck.Check(href, refs.Host, fb.PromoPaths, fb.PromoExtraParameters); + if (v.Ok) candidates.Add(new RedeemCandidate(v.Link!, "campanella", 0, false, 0)); + else rejected++; + } + } + var known = await KnownAsync(candidates.Select(c => c.Link.Code).Distinct().ToArray(), ct).ConfigureAwait(false); var s = _settings(); var plan = RedeemPlanner.Choose(candidates, known, new RedeemLimits(s.FreeBidsMaxPerRun, s.FreeBidsMaxPerDay, s.FreeBidsMaxAttempts), @@ -325,6 +400,18 @@ public sealed class FreeBidsService : IDisposable return rows.ToDictionary(x => x.Code, x => new KnownCode(x.N, x.Final), StringComparer.Ordinal); } + private async Task<(int Count, int Gained)> CreditedTodayWithGainAsync(CancellationToken ct) + { + ct.ThrowIfCancellationRequested(); + var midnight = TimeZoneInfo.ConvertTimeToUtc(AppInfo.LocalNow.Date, AppInfo.TimeZone); + var rows = await _db.QueryAsync( + "SELECT count(*)::int AS n, coalesce(sum(gained) FILTER (WHERE gained > 0), 0)::int AS g FROM promo_redemptions " + + "WHERE ts >= $1 AND outcome = ANY($2)", + r => (r.Int("n"), r.Int("g")), midnight, + new[] { OutcomeCode(RedeemOutcome.Credited), OutcomeCode(RedeemOutcome.CreditedWithWarning) }).ConfigureAwait(false); + return rows.Count > 0 ? rows[0] : (0, 0); + } + private async Task CreditedTodayAsync(CancellationToken ct) { ct.ThrowIfCancellationRequested(); diff --git a/src/Mimante/Bidoo/FreeBids/RewardsPages.cs b/src/Mimante/Bidoo/FreeBids/RewardsPages.cs new file mode 100644 index 0000000..f153e4f --- /dev/null +++ b/src/Mimante/Bidoo/FreeBids/RewardsPages.cs @@ -0,0 +1,194 @@ +using System.Globalization; +using System.Net; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace Mimante.Bidoo.FreeBids; + +/// +/// Una ricompensa che Bidoo ha accreditato davvero: un forziere (/my_chests.php) o un movimento della +/// cronologia crediti (/bids_history.php). la rende unica in account_rewards. +/// : per i forzieri come sono stati ottenuti («link», «aste di puntate confermate»…). +/// +public sealed record AccountReward(string Key, string Kind, DateTime AtUtc, int Bids, bool Free, string Source, string Description); + +/// Quello che si legge da una delle due pagine: le ricompense, o perché non si è letta. +public sealed record RewardsRead(IReadOnlyList Items, string? Error, int Skipped = 0); + +/// I collegamenti promozionali trovati nella campanella, con l'id della notifica che li contiene. +public sealed record NotificationLinks(int Notifications, IReadOnlyList<(string Id, string Href)> Links, string? Error); + +/// +/// Le pagine delle ricompense e la campanella di Bidoo (issue #38). Pure, sotto test con copie della struttura +/// vera (valori inventati). Le date dei forzieri sono scritte in italiano, ora di Roma; quelle della cronologia +/// sono nello script della pagina, in secondi Unix, legate all'id del movimento. +/// +public static class RewardsPages +{ + public const string KindChest = "forziere"; + public const string KindCredit = "accredito"; + + private const RegexOptions Opt = RegexOptions.CultureInvariant | RegexOptions.Singleline | RegexOptions.IgnoreCase; + private static readonly string[] Months = + ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"]; + + private static readonly Regex ChestItem = new(@"(.*?)", Opt); + private static readonly Regex ChestPoints = new(@"\s*\s*\+?\s*(\d+)\s*.*?\s*([^<]+?)\s*", Opt); + private static readonly Regex ItalianDate = new(@"(\d{1,2})\s+(" + string.Join('|', Months) + @")\s+(\d{4})(?:\s+alle)?\s+(\d{1,2}):(\d{2})", Opt); + private static readonly Regex ChestSource = new(@"tramite\s+(.+?)\s+il\s+\d", Opt); + + private static readonly Regex CreditTable = new(@"]*class=""[^""]*my-bidoo-table[^""]*""[^>]*>(.*?)", Opt); + private static readonly Regex Row = new(@"]*>(.*?)", Opt); + private static readonly Regex MovementId = new(@"id=""data_mov(\d+)""", Opt); + private static readonly Regex FirstRow = new(@"(.*?)", Opt); + private static readonly Regex SecondRow = new(@"(.*?)", Opt); + private static readonly Regex Total = new(@"(.*?)", Opt); + private static readonly Regex MovementTime = new(@"'data_mov'\s*\+\s*(\d+)\s*\)\s*\)\s*\{[^}]*?formattaDataStorico\(\s*(\d+)", Opt); + private static readonly Regex LeadingNumber = new(@"^\s*(\d[\d.]*)", Opt); + + private static readonly Regex Tags = new("<[^>]+>", Opt); + private static readonly Regex Spaces = new(@"\s+", Opt); + private static readonly Regex Href = new(@"href\s*=\s*[""']([^""']+)[""']", Opt); + private static readonly Regex BareUrl = new(@"https?://[^\s""'<>]+", Opt); + + // ── /my_chests.php ──────────────────────────────────────────────── + + /// + /// I forzieri aperti: ogni wrap-item con il testo («Ottenuto tramite link il 9 Novembre 2026 alle 14:05») + /// e il premio (pt-chest, «+3 Puntate»). Un forziere senza premio (ancora da aprire o scaduto) si salta. + /// Due forzieri uguali nello stesso minuto restano due: la chiave porta il numero d'ordine. + /// + public static RewardsRead ParseChests(string? html, TimeZoneInfo tz) + { + if (string.IsNullOrEmpty(html) || !html.Contains("items-sections", StringComparison.OrdinalIgnoreCase)) + return new([], "la pagina delle ricompense non ha l'elenco dei forzieri: sessione scaduta o formato cambiato?"); + var starts = ChestItem.Matches(html).Select(m => m.Index).ToList(); + var items = new List(); + var seen = new Dictionary(StringComparer.Ordinal); + var skipped = 0; + for (var i = 0; i < starts.Count; i++) + { + var block = html[starts[i]..(i + 1 < starts.Count ? starts[i + 1] : html.Length)]; + var points = ChestPoints.Match(block); + if (!points.Success) continue; + var text = Clean(ChestText.Match(block).Groups[1].Value); + var date = ItalianDate.Match(text); + if (!date.Success) { skipped++; continue; } + var local = new DateTime(int.Parse(date.Groups[3].Value, CultureInfo.InvariantCulture), + Array.IndexOf(Months, date.Groups[2].Value.ToLowerInvariant()) + 1, int.Parse(date.Groups[1].Value, CultureInfo.InvariantCulture), + int.Parse(date.Groups[4].Value, CultureInfo.InvariantCulture), int.Parse(date.Groups[5].Value, CultureInfo.InvariantCulture), 0, + DateTimeKind.Unspecified); + var amount = int.Parse(points.Groups[1].Value, CultureInfo.InvariantCulture); + var unit = Clean(points.Groups[2].Value); + var isBids = unit.StartsWith("puntat", StringComparison.OrdinalIgnoreCase); + var source = ChestSource.Match(text) is { Success: true } s ? Clean(s.Groups[1].Value).ToLowerInvariant() : ""; + var baseKey = $"{KindChest}|{local:yyyy-MM-ddTHH:mm}|{source}|{amount} {unit.ToLowerInvariant()}"; + var n = seen.GetValueOrDefault(baseKey); + seen[baseKey] = n + 1; + items.Add(new AccountReward($"{baseKey}|{n}", KindChest, ToUtc(local, tz), isBids ? amount : 0, true, source, + $"{text} (+{amount} {unit})")); + } + return new(items, null, skipped); + } + + // ── /bids_history.php ───────────────────────────────────────────── + + /// + /// La cronologia crediti: una riga per movimento (data_mov<id>), descrizione («3 Gratis»), totale + /// («Gratis» o un prezzo). L'ora la scrive lo script della pagina: 'data_mov' + id … formattaDataStorico(unix. + /// + public static RewardsRead ParseCreditHistory(string? html) + { + if (string.IsNullOrEmpty(html) || CreditTable.Match(html) is not { Success: true } table) + return new([], "la cronologia crediti non ha la tabella dei movimenti: sessione scaduta o formato cambiato?"); + var times = new Dictionary(StringComparer.Ordinal); + foreach (Match m in MovementTime.Matches(html)) + times[m.Groups[1].Value] = long.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture); + + var items = new List(); + var skipped = 0; + foreach (Match row in Row.Matches(table.Groups[1].Value)) + { + var cells = row.Groups[1].Value; + if (MovementId.Match(cells) is not { Success: true } id) continue; // l'intestazione + if (!times.TryGetValue(id.Groups[1].Value, out var unix)) { skipped++; continue; } + var first = Clean(FirstRow.Match(cells).Groups[1].Value); + var second = Clean(SecondRow.Match(cells).Groups[1].Value); + var total = Clean(Total.Match(cells).Groups[1].Value); + var bids = LeadingNumber.Match(first) is { Success: true } b + && int.TryParse(b.Groups[1].Value.Replace(".", ""), NumberStyles.None, CultureInfo.InvariantCulture, out var v) ? v : 0; + var free = total.Contains("gratis", StringComparison.OrdinalIgnoreCase); + var description = string.Join(" · ", new[] { first, second, total }.Where(x => x.Length > 0)); + items.Add(new AccountReward($"{KindCredit}|{id.Groups[1].Value}", KindCredit, + DateTimeOffset.FromUnixTimeSeconds(unix).UtcDateTime, bids, free, "", description)); + } + return new(items, null, skipped); + } + + // ── /checkN.php ─────────────────────────────────────────────────── + + /// + /// La campanella: {"count":…, "elements": {…} | […]}, ogni notifica con id e content in HTML. + /// Si tengono solo gli indirizzi con promocode: poi passano dallo stesso controllo dei collegamenti della fonte. + /// + public static NotificationLinks ParseNotifications(string? json) + { + try + { + using var doc = JsonDocument.Parse(string.IsNullOrWhiteSpace(json) ? "null" : json); + if (doc.RootElement.ValueKind != JsonValueKind.Object || !doc.RootElement.TryGetProperty("elements", out var els)) + return new(0, [], "risposta della campanella senza elements: sessione scaduta o formato cambiato?"); + var list = els.ValueKind switch + { + JsonValueKind.Array => els.EnumerateArray().ToList(), + JsonValueKind.Object => els.EnumerateObject().Select(p => p.Value).ToList(), + _ => [] + }; + var links = new List<(string, string)>(); + var count = 0; + foreach (var e in list.Where(x => x.ValueKind == JsonValueKind.Object)) + { + count++; + var id = e.TryGetProperty("id", out var idv) ? idv.ToString() : ""; + var content = e.TryGetProperty("content", out var c) && c.ValueKind == JsonValueKind.String ? c.GetString() ?? "" : ""; + var found = Href.Matches(content).Select(m => m.Groups[1].Value) + .Concat(BareUrl.Matches(Tags.Replace(content, " ")).Select(m => m.Value)) + .Select(h => WebUtility.HtmlDecode(h) ?? "") + .Where(h => h.Contains("promocode", StringComparison.OrdinalIgnoreCase)) + .Distinct(StringComparer.Ordinal); + foreach (var h in found) links.Add((id, h)); + } + return new(count, links, null); + } + catch (JsonException) + { + return new(0, [], "la campanella non ha risposto con JSON: sessione scaduta o formato cambiato?"); + } + } + + // ── confronto ───────────────────────────────────────────────────── + + /// + /// Il confronto del giorno fra ciò che Bidoo segna come ottenuto tramite collegamento e i riscatti riusciti del bot. + /// Una differenza non è per forza un errore: un collegamento aperto a mano dal telefono conta per Bidoo, non per il bot. + /// + public static string CompareToday(IEnumerable rewards, DateOnly today, TimeZoneInfo tz, int redeemed, int gained) + { + var fromLinks = rewards.Where(r => r.Kind == KindChest && r.Source == "link" + && DateOnly.FromDateTime(TimeZoneInfo.ConvertTimeFromUtc(r.AtUtc, tz)) == today).ToList(); + var bids = fromLinks.Sum(r => r.Bids); + var head = $"oggi Bidoo segna {fromLinks.Count} ricompense da collegamento (+{bids} puntate), il bot ha {redeemed} riscatti riusciti (+{gained} dal saldo)"; + return fromLinks.Count == redeemed && bids == gained ? head + ": tornano" + : fromLinks.Count > redeemed ? head + ": gli altri sono collegamenti aperti fuori dal bot o accrediti non visti dal saldo" + : head + ": qualche riscatto del bot non compare fra le ricompense"; + } + + private static DateTime ToUtc(DateTime local, TimeZoneInfo tz) + { + try { return TimeZoneInfo.ConvertTimeToUtc(local, tz); } + catch (ArgumentException) { return TimeZoneInfo.ConvertTimeToUtc(local.AddHours(1), tz); } // ora che non esiste (cambio d'ora) + } + + private static string Clean(string html) => Spaces.Replace(WebUtility.HtmlDecode(Tags.Replace(html, " ")), " ").Trim(); +} diff --git a/src/Mimante/Bidoo/bidoo.default.json b/src/Mimante/Bidoo/bidoo.default.json index 44f0da7..c4483d5 100644 --- a/src/Mimante/Bidoo/bidoo.default.json +++ b/src/Mimante/Bidoo/bidoo.default.json @@ -149,6 +149,10 @@ // Forzieri: per ogni categoria {"url": null} o {"url": "…"}. Tag 0 più le categorie della home. "chestTag": "/ajax/chest/get_chest_tag_url.php?tag={tag}", "chestTags": [ 0, 6, 5, 7, 13, 18, 8, 11, 40, 44, 9, 14, 41, 21, 19, 20, 22, 10, 37, 12 ], - "rewardsPage": "/my_chests.php" + // Le ricompense ottenute (forzieri) e la cronologia crediti: si leggono a intervalli per il confronto con i riscatti. + "rewardsPage": "/my_chests.php", + "creditsHistoryPage": "/bids_history.php", + // La campanella, seconda fonte di collegamenti. Solo lettura: _d=1 e _r=1 segnerebbero le notifiche, il bot non li usa. + "notifications": "/checkN.php" } } diff --git a/src/Mimante/Data/Archive/ArchiveTables.cs b/src/Mimante/Data/Archive/ArchiveTables.cs index b8668e1..c92971f 100644 --- a/src/Mimante/Data/Archive/ArchiveTables.cs +++ b/src/Mimante/Data/Archive/ArchiveTables.cs @@ -70,6 +70,8 @@ public sealed record ArchiveTable( new("promo_redemptions", ArchiveSplit.Whole, null, "id", "I riscatti delle puntate gratuite: codice, fonte, esito di Bidoo, saldo prima e dopo, puntate guadagnate."), new("chests", ArchiveSplit.Whole, null, "id", "I forzieri visti nelle categorie (solo avviso), per giorno."), + new("account_rewards", ArchiveSplit.Whole, null, "id", + "Le ricompense che Bidoo ha accreditato, lette dalle sue pagine: forzieri aperti e movimenti della cronologia crediti."), new("schema_migrations", ArchiveSplit.Whole, null, "version", "Le migrazioni applicate all'archivio."), new("settings", ArchiveSplit.Whole, null, "id", "Le impostazioni del bot, senza token e chat di Telegram.", Expressions: _ => new Dictionary { ["value"] = "value - 'TelegramBotToken' - 'TelegramChatId'" }), diff --git a/src/Mimante/Data/Migrations/0006_ricompense.sql b/src/Mimante/Data/Migrations/0006_ricompense.sql new file mode 100644 index 0000000..15293db --- /dev/null +++ b/src/Mimante/Data/Migrations/0006_ricompense.sql @@ -0,0 +1,18 @@ +-- Ricompense accreditate da Bidoo (issue #38, ADR 0015). Solo una tabella nuova. + +-- Serve allo storico per: ciò che Bidoo ha davvero accreditato, letto dalle sue pagine (forzieri da +-- /my_chests.php, movimenti gratuiti da /bids_history.php), da confrontare con i riscatti tentati in +-- promo_redemptions: dice quanto rende il riscatto e se un accredito sfugge al saldo. Una riga per +-- ricompensa, mai riscritta (key unica: forziere con data, fonte, premio e ordine; movimento con il suo id). +CREATE TABLE IF NOT EXISTS account_rewards ( + id bigserial PRIMARY KEY, + key text NOT NULL UNIQUE, + kind text NOT NULL, + ts timestamptz NOT NULL, + bids int NOT NULL, + free boolean NOT NULL, + source text NOT NULL, + description text NOT NULL, + seen_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX IF NOT EXISTS account_rewards_ts ON account_rewards(ts); diff --git a/src/Mimante/Host/BotWorld.cs b/src/Mimante/Host/BotWorld.cs index 3e443c7..fbb9a03 100644 --- a/src/Mimante/Host/BotWorld.cs +++ b/src/Mimante/Host/BotWorld.cs @@ -202,6 +202,7 @@ public sealed class BotWorld : IAsyncDisposable { _jobs.Add(FreeBids.RunAsync(ct)); _jobs.Add(FreeBids.RunChestsAsync(ct)); + _jobs.Add(FreeBids.RunRewardsAsync(ct)); } bot.Log.Info("AVVIO", IsSimulator ? "Modalità debug: stai vedendo il simulatore (nessuna sessione Bidoo salvata)" diff --git a/src/Mimante/Settings/AppSettings.cs b/src/Mimante/Settings/AppSettings.cs index 8d13f72..be22752 100644 --- a/src/Mimante/Settings/AppSettings.cs +++ b/src/Mimante/Settings/AppSettings.cs @@ -208,6 +208,12 @@ public sealed class AppSettings public int FreeBidsHoursStart { get; set; } = 8; public int FreeBidsHoursEnd { get; set; } = 24; + /// La campanella di Bidoo come seconda fonte di collegamenti (letta senza segnare le notifiche). + public bool FreeBidsUseNotifications { get; set; } = true; + + /// Ore fra una lettura delle ricompense (forzieri e cronologia crediti) e l'altra; 0 = mai. + public int FreeBidsRewardsHours { get; set; } = 6; + /// Giro delle categorie per i forzieri: solo avviso, il bot non li apre. public bool ChestWatchEnabled { get; set; } diff --git a/src/Mimante/Settings/SettingsStore.cs b/src/Mimante/Settings/SettingsStore.cs index 69e12f6..8968593 100644 --- a/src/Mimante/Settings/SettingsStore.cs +++ b/src/Mimante/Settings/SettingsStore.cs @@ -216,6 +216,7 @@ public sealed class SettingsStore s.FreeBidsHoursStart = Math.Clamp(s.FreeBidsHoursStart, 0, 24); s.FreeBidsHoursEnd = Math.Clamp(s.FreeBidsHoursEnd, 0, 24); s.ChestWatchMinutes = Math.Clamp(s.ChestWatchMinutes, 5, 24 * 60); + s.FreeBidsRewardsHours = Math.Clamp(s.FreeBidsRewardsHours, 0, 7 * 24); s.SuggestedCoveragePercent = Math.Clamp(s.SuggestedCoveragePercent, 50, 99); s.SuggestedValueTolerancePercent = Math.Clamp(s.SuggestedValueTolerancePercent, 0, 100); diff --git a/src/Mimante/Web/Api.cs b/src/Mimante/Web/Api.cs index 34ec84b..fb79f07 100644 --- a/src/Mimante/Web/Api.cs +++ b/src/Mimante/Web/Api.cs @@ -358,12 +358,21 @@ public static class Api ["first"] = r.Date("first_seen"), ["last"] = r.Date("last_seen"), ["tag"] = r.Int("tag"), ["url"] = r.Str("url") }).ConfigureAwait(false); + var rewards = await bot.Db.QueryAsync( + "SELECT ts, kind, bids, free, source, description FROM account_rewards ORDER BY ts DESC, id DESC LIMIT 300", + r => new Dictionary + { + ["at"] = r.Date("ts"), ["kind"] = r.Str("kind"), ["bids"] = r.Int("bids"), ["free"] = r.BoolOrNull("free") ?? false, + ["source"] = r.Str("source"), ["description"] = r.Str("description") + }).ConfigureAwait(false); + return new Dictionary { ["present"] = service != null, ["counts"] = counts, ["redemptions"] = redemptions, ["chests"] = chests, + ["rewards"] = rewards, ["log"] = service?.Lines(500).Select(l => new Dictionary { ["at"] = l.AtUtc, ["text"] = l.Text }).ToList() }; } diff --git a/src/Mimante/Web/Views.cs b/src/Mimante/Web/Views.cs index e59afd7..848fd1b 100644 --- a/src/Mimante/Web/Views.cs +++ b/src/Mimante/Web/Views.cs @@ -196,6 +196,8 @@ public static class Views ["chestWatch"] = s.ChestWatch, ["lastChestAt"] = s.LastChestUtc, ["chestsToday"] = s.ChestsToday, + ["lastRewardsAt"] = s.LastRewardsUtc, + ["rewardsSummary"] = s.RewardsSummary, ["log"] = service.Lines(60).Select(l => new Dictionary { ["at"] = l.AtUtc, ["text"] = l.Text }).ToList() }; } diff --git a/src/Mimante/wwwroot/js/pages/impostazioni.js b/src/Mimante/wwwroot/js/pages/impostazioni.js index da49fd1..7e549c3 100644 --- a/src/Mimante/wwwroot/js/pages/impostazioni.js +++ b/src/Mimante/wwwroot/js/pages/impostazioni.js @@ -91,6 +91,8 @@ const sections = [ ['FreeBidsPauseMaxSeconds', 'Pausa fra riscatti: a s', I, 'Non meno della pausa minima'], ['FreeBidsHoursStart', 'Riscatta dalle ore', I, 'Ora di Roma, compresa; uguale alla fine = sempre'], ['FreeBidsHoursEnd', 'Riscatta fino alle ore', I, 'Ora di Roma, esclusa (24 = fino a mezzanotte)'], + ['FreeBidsUseNotifications', 'Anche dalla campanella', B, 'Cerca collegamenti anche nelle notifiche di Bidoo; le legge senza segnarle come lette'], + ['FreeBidsRewardsHours', 'Ricompense: lettura ogni ore', I, 'Legge forzieri e cronologia crediti di Bidoo e li confronta con i riscatti; 0 = mai'], ['ChestWatchEnabled', 'Avviso forzieri', B, 'Il bot guarda le categorie e avvisa di un forziere: non lo apre'], ['ChestWatchMinutes', 'Forzieri: un giro ogni min', I, 'Minimo 5'], ['TelegramNotifyFreeBids', 'Messaggio su Telegram', B, 'Per ogni riscatto riuscito, per una pausa del riscatto e per un forziere trovato'] diff --git a/src/Mimante/wwwroot/js/pages/puntate-gratis.js b/src/Mimante/wwwroot/js/pages/puntate-gratis.js index 105c1cc..23cdecc 100644 --- a/src/Mimante/wwwroot/js/pages/puntate-gratis.js +++ b/src/Mimante/wwwroot/js/pages/puntate-gratis.js @@ -41,6 +41,7 @@ export async function mount(host) { ui.tabs = el('div', { class: 'tabs', role: 'tablist' }, tabButton('riscatti', 'Puntate riscattate', 'Ogni riscatto tentato, con l\'esito di Bidoo e il saldo prima e dopo'), + tabButton('ricompense', 'Ricompense di Bidoo', 'Quello che Bidoo ha accreditato davvero: forzieri aperti e movimenti gratuiti della cronologia crediti, letti a intervalli'), tabButton('forzieri', 'Forzieri', 'I forzieri visti nelle categorie (solo avviso)'), tabButton('registro', 'Registro', 'Le operazioni del riscatto e dei forzieri, una riga per evento (anche nel file riscatti-AAAA-MM-GG.log)')); ui.body = el('div', { class: 'in', style: { maxHeight: 'none' } }); @@ -106,8 +107,9 @@ function paint(f) { if (f.nextRunAt && f.enabled) parts.push('prossimo ' + when(f.nextRunAt)); parts.push(f.confirmed ? 'accredito confermato dal saldo' : 'un collegamento per giro finché il saldo non conferma'); if (f.chestWatch) parts.push(`forzieri: ${num(f.chestsToday)} oggi` + (f.lastChestAt ? `, ultimo giro ${when(f.lastChestAt)}` : '')); + if (f.lastRewardsAt) parts.push('ricompense lette ' + when(f.lastRewardsAt)); ui.status.textContent = parts.join(' · '); - if (f.lastSummary) ui.status.title = 'Ultimo giro: ' + f.lastSummary; + ui.status.title = [f.lastSummary ? 'Ultimo giro: ' + f.lastSummary : '', f.rewardsSummary ? 'Ricompense: ' + f.rewardsSummary : ''].filter(Boolean).join('\n'); ui.pause.hidden = !f.paused; ui.resume.hidden = !f.paused; if (f.paused) ui.pause.textContent = 'In pausa: ' + (f.pauseReason || 'motivo non registrato') + '. Controlla su Bidoo, poi togli la pausa.'; @@ -150,6 +152,7 @@ function paintBody() { if (!ui.body || !data) return; if (tab === 'riscatti') ui.body.replaceChildren(redemptions(data.redemptions || [])); else if (tab === 'forzieri') ui.body.replaceChildren(chests(data.chests || [])); + else if (tab === 'ricompense') ui.body.replaceChildren(rewards(data.rewards || [])); else ui.body.replaceChildren(logLines(data.log || [])); } @@ -189,6 +192,22 @@ function chests(rows) { el('td', null, el('a', { href: r.url, target: '_blank', rel: 'noopener noreferrer', title: 'Apri il forziere su Bidoo (nel tuo browser)' }, r.url)))))); } +function rewards(rows) { + const f = state.freebids || {}; + const head = f.rewardsSummary ? el('p', { class: 'help note', title: 'L\'ultima lettura delle pagine di Bidoo e il confronto con i riscatti del bot' }, f.rewardsSummary) : ''; + if (!rows.length) return el('div', null, head, el('span', { class: 'help' }, 'Nessuna ricompensa letta finora: il bot legge forzieri e cronologia crediti di Bidoo a intervalli (Impostazioni ▸ Puntate gratis), con l\'utente collegato.')); + return el('div', null, head, el('table', { class: 'grid' }, + el('thead', null, el('tr', null, th('Quando', 'Quando Bidoo ha accreditato la ricompensa'), th('Tipo', 'Forziere aperto o movimento della cronologia crediti'), + th('Ottenuto con', 'Per i forzieri: come è stato ottenuto (link, aste di puntate confermate…)'), + th('Puntate', 'Puntate accreditate', 'num'), th('Descrizione', 'Il testo di Bidoo'))), + el('tbody', null, rows.map(r => el('tr', null, + el('td', { title: when(r.at) }, time(r.at)), + el('td', null, r.kind), + el('td', null, r.source || ''), + el('td', { class: 'num ' + (r.free && r.bids > 0 ? 'ok' : '') , title: r.free ? 'Gratuite' : 'A pagamento' }, r.bids ? (r.free ? '+' : '') + num(r.bids) : ''), + el('td', { class: 'sub' }, r.description)))))); +} + function logLines(rows) { if (!rows.length) return el('span', { class: 'help' }, 'Nessuna operazione dall\'avvio del bot. Il file riscatti-AAAA-MM-GG.log è nella pagina Registro.'); return el('div', { class: 'log', style: { fontFamily: 'var(--mono)', lineHeight: '1.55' } }, diff --git a/tests/Mimante.Tests/Fixtures/campanella.json b/tests/Mimante.Tests/Fixtures/campanella.json new file mode 100644 index 0000000..ae450bf --- /dev/null +++ b/tests/Mimante.Tests/Fixtures/campanella.json @@ -0,0 +1 @@ +{"count":3,"elements":{"0":{"id":"9000003","users":"0","type":"9","arguments":"","created_at":"1795511000","visibleFor":"0","readFlag":"0","content":"

Solo per oggi: 5 puntate gratis per te!<\/p><\/a>"},"1":{"id":"9000002","users":"0","type":"6","arguments":"","created_at":"1795470000","visibleFor":"0","readFlag":"1","content":"\n

Sul tuo conto Bidoo Shop è stato accreditato l'importo di 10.00 €<\/p><\/a>"},"2":{"id":"9000001","users":"0","type":"9","arguments":"","created_at":"1795400000","visibleFor":"0","readFlag":"2","content":"

Copia questo indirizzo: https:\/\/it.bidoo.com\/index.php?promocode=altro241126&sign=89abcdef0123456789abcdef0123456789abcdef<\/p>"}},"audio":"","exceed":22,"shexc":22,"t":1795541810} diff --git a/tests/Mimante.Tests/Fixtures/cronologia-crediti.html b/tests/Mimante.Tests/Fixtures/cronologia-crediti.html new file mode 100644 index 0000000..edce1f2 --- /dev/null +++ b/tests/Mimante.Tests/Fixtures/cronologia-crediti.html @@ -0,0 +1,42 @@ + + + +My Bidoo - Cronologia Crediti - Bidoo + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DataDescrizionePrezzo
5 Gratis
Gratis
2 Gratis
Gratis
1.000 Puntate
Pacchetto
100,00 €
3 Gratis
Gratis
+

+ + + diff --git a/tests/Mimante.Tests/Fixtures/ricompense-forzieri.html b/tests/Mimante.Tests/Fixtures/ricompense-forzieri.html new file mode 100644 index 0000000..9227988 --- /dev/null +++ b/tests/Mimante.Tests/Fixtures/ricompense-forzieri.html @@ -0,0 +1,49 @@ + + + +My Bidoo - Le mie ricompense - Bidoo + +
+
Cronologia
+
+
+
+
+
+
Ottenuto tramite link il 24 Novembre 2026 alle 09:05
+
+5 Puntate
+ +
+
+
+
+
+
Ottenuto tramite link il 24 Novembre 2026 alle 09:05
+
+5 Puntate
+
+
+
+
+
+
Ottenuto tramite link il 23 Novembre 2026 alle 21:40
+
+2 Puntate
+
+
+
+
+
+
Ottenuto tramite aste di puntate confermate il 3 Novembre 2026 alle 18:12
+
+15 Puntate
+
+
+
+
+
+
Dal forziere del 2 Novembre 2026 10:30
+
+
+
+
+
+ + diff --git a/tests/Mimante.Tests/RewardsPagesTests.cs b/tests/Mimante.Tests/RewardsPagesTests.cs new file mode 100644 index 0000000..d25816b --- /dev/null +++ b/tests/Mimante.Tests/RewardsPagesTests.cs @@ -0,0 +1,99 @@ +using Mimante.Bidoo; +using Mimante.Bidoo.FreeBids; +using Xunit; + +namespace Mimante.Tests; + +/// Ricompense, cronologia crediti e campanella di Bidoo (#38): copie della struttura vera, valori inventati. +public class RewardsPagesTests +{ + private static readonly TimeZoneInfo Rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"); + + private static string Fixture(string name) => File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", name)); + + [Fact] + public void I_forzieri_aperti_con_data_fonte_e_premio() + { + var read = RewardsPages.ParseChests(Fixture("ricompense-forzieri.html"), Rome); + Assert.Null(read.Error); + Assert.Equal(4, read.Items.Count); // quello senza premio non conta + + var first = read.Items[0]; + Assert.Equal(RewardsPages.KindChest, first.Kind); + Assert.Equal(new DateTime(2026, 11, 24, 8, 5, 0, DateTimeKind.Utc), first.AtUtc); // 09:05 a Roma + Assert.Equal(5, first.Bids); + Assert.True(first.Free); + Assert.Equal("link", first.Source); + Assert.Contains("+5 Puntate", first.Description); + + // Due forzieri uguali nello stesso minuto restano due. + Assert.NotEqual(read.Items[0].Key, read.Items[1].Key); + Assert.Equal(read.Items.Count, read.Items.Select(i => i.Key).Distinct().Count()); + + Assert.Equal("aste di puntate confermate", read.Items[3].Source); + Assert.Equal(15, read.Items[3].Bids); + } + + [Fact] + public void La_cronologia_crediti_prende_l_ora_dallo_script_della_pagina() + { + var read = RewardsPages.ParseCreditHistory(Fixture("cronologia-crediti.html")); + Assert.Null(read.Error); + Assert.Equal(3, read.Items.Count); + Assert.Equal(1, read.Skipped); // il movimento senza ora nello script + + var free = read.Items[0]; + Assert.Equal("accredito|1000000003", free.Key); + Assert.Equal(DateTimeOffset.FromUnixTimeSeconds(1795511512).UtcDateTime, free.AtUtc); + Assert.Equal(5, free.Bids); + Assert.True(free.Free); + + var paid = read.Items[2]; + Assert.Equal(1000, paid.Bids); + Assert.False(paid.Free); + Assert.Contains("Pacchetto", paid.Description); + Assert.Contains("100,00 €", paid.Description); + } + + [Fact] + public void La_campanella_da_solo_i_collegamenti_promozionali_e_passano_il_controllo() + { + var bell = RewardsPages.ParseNotifications(Fixture("campanella.json")); + Assert.Null(bell.Error); + Assert.Equal(3, bell.Notifications); + Assert.Equal(2, bell.Links.Count); + Assert.Equal("9000003", bell.Links[0].Id); + Assert.Equal("https://it.bidoo.com/?promocode=prova241126&sign=0123456789abcdef0123456789abcdef01234567", bell.Links[0].Href); + Assert.Equal("9000001", bell.Links[1].Id); // indirizzo scritto nel testo, senza href + + var fb = BidooReferences.Default.FreeBids; + foreach (var (_, href) in bell.Links) + Assert.True(PromoLinkCheck.Check(href, BidooReferences.Default.Host, fb.PromoPaths, fb.PromoExtraParameters).Ok, href); + + Assert.Empty(RewardsPages.ParseNotifications("""{"count":0,"elements":[],"t":1}""").Links); + } + + [Fact] + public void Una_pagina_di_accesso_o_una_risposta_rotta_si_dicono_e_non_danno_ricompense() + { + const string login = "
"; + Assert.NotNull(RewardsPages.ParseChests(login, Rome).Error); + Assert.NotNull(RewardsPages.ParseCreditHistory(login).Error); + Assert.NotNull(RewardsPages.ParseChests(null, Rome).Error); + Assert.NotNull(RewardsPages.ParseNotifications(login).Error); + Assert.NotNull(RewardsPages.ParseNotifications("""{"count":0}""").Error); + Assert.Empty(RewardsPages.ParseNotifications("rotto").Links); + } + + [Fact] + public void Il_confronto_del_giorno_con_i_riscatti_del_bot() + { + var items = RewardsPages.ParseChests(Fixture("ricompense-forzieri.html"), Rome).Items; + var today = new DateOnly(2026, 11, 24); + Assert.EndsWith("tornano", RewardsPages.CompareToday(items, today, Rome, 2, 10)); + Assert.Contains("2 ricompense da collegamento (+10 puntate)", RewardsPages.CompareToday(items, today, Rome, 2, 10)); + Assert.Contains("fuori dal bot", RewardsPages.CompareToday(items, today, Rome, 1, 5)); + Assert.Contains("non compare", RewardsPages.CompareToday(items, today, Rome, 3, 15)); + Assert.Contains("1 ricompense da collegamento (+2 puntate)", RewardsPages.CompareToday(items, today.AddDays(-1), Rome, 1, 2)); + } +}