Ricompense di Bidoo e campanella come seconda fonte del riscatto (#38)
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
88c16568fb
commit
6cbc5e58b0
22 files changed
+590
-12
No files matched your search
+4
-1
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
@@ -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`,
|
||||
|
||||
+2
-2
@@ -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
|
||||
|
||||
@@ -42,6 +42,34 @@ public sealed partial class BidooApi
|
||||
page.StatusCode, page.LatencyMs + answer.LatencyMs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Una pagina del conto (ricompense, cronologia crediti) come documento, con la sessione: il testo, o perché
|
||||
/// non si è letta. Non passa da <c>CheckSession</c>: 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// La campanella (<c>/checkN.php</c> 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 <c>_d=1</c> e <c>_r=1&l=…</c>,
|
||||
/// due richieste separate che il bot non fa mai.
|
||||
/// </summary>
|
||||
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());
|
||||
}
|
||||
|
||||
/// <summary>Se in una categoria c'è un forziere: <c>{"url": null}</c> o <c>{"url": "…"}</c>. Non serve la sessione.</summary>
|
||||
public async Task<ChestProbe> ProbeChestAsync(int tag, CancellationToken ct)
|
||||
{
|
||||
|
||||
@@ -39,6 +39,8 @@ public sealed class BidooReferences
|
||||
public string ChestTag { get; set; } = "";
|
||||
public List<int> ChestTags { get; set; } = new();
|
||||
public string RewardsPage { get; set; } = "";
|
||||
public string CreditsHistoryPage { get; set; } = "";
|
||||
public string Notifications { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>L'host di Bidoo (da <see cref="BaseUrl"/>): l'unico su cui si apre un collegamento promozionale.</summary>
|
||||
|
||||
@@ -37,7 +37,8 @@ public sealed class FreeBidsService : IDisposable
|
||||
|
||||
/// <summary>Come sta il servizio, per l'interfaccia.</summary>
|
||||
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<string> _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<BidooReferences> refs, Func<AppSettings> 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);
|
||||
}
|
||||
|
||||
/// <summary>Toglie la pausa (dalla pagina): il prossimo giro riparte con un collegamento solo, finché il saldo non conferma.</summary>
|
||||
@@ -148,6 +149,66 @@ public sealed class FreeBidsService : IDisposable
|
||||
}
|
||||
}, ct);
|
||||
|
||||
/// <summary>La lettura delle ricompense, a intervalli di ore, se accesa e con l'utente collegato.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// Legge le ricompense ottenute (forzieri) e la prima pagina della cronologia crediti, salva le nuove in
|
||||
/// <c>account_rewards</c> e confronta quelle di oggi da collegamento con i riscatti riusciti del bot.
|
||||
/// </summary>
|
||||
public async Task<string> SyncRewardsAsync(CancellationToken ct)
|
||||
{
|
||||
if (!_canRedeem()) return "nessuna lettura: serve l'utente di Bidoo collegato";
|
||||
var fb = _refs().FreeBids;
|
||||
var all = new List<AccountReward>();
|
||||
var problems = new List<string>();
|
||||
|
||||
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<string>(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<int> CreditedTodayAsync(CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Mimante.Bidoo.FreeBids;
|
||||
|
||||
/// <summary>
|
||||
/// Una ricompensa che Bidoo ha accreditato davvero: un forziere (<c>/my_chests.php</c>) o un movimento della
|
||||
/// cronologia crediti (<c>/bids_history.php</c>). <paramref name="Key"/> la rende unica in <c>account_rewards</c>.
|
||||
/// <paramref name="Source"/>: per i forzieri come sono stati ottenuti («link», «aste di puntate confermate»…).
|
||||
/// </summary>
|
||||
public sealed record AccountReward(string Key, string Kind, DateTime AtUtc, int Bids, bool Free, string Source, string Description);
|
||||
|
||||
/// <summary>Quello che si legge da una delle due pagine: le ricompense, o perché non si è letta.</summary>
|
||||
public sealed record RewardsRead(IReadOnlyList<AccountReward> Items, string? Error, int Skipped = 0);
|
||||
|
||||
/// <summary>I collegamenti promozionali trovati nella campanella, con l'id della notifica che li contiene.</summary>
|
||||
public sealed record NotificationLinks(int Notifications, IReadOnlyList<(string Id, string Href)> Links, string? Error);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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(@"<div\s+class=""wrap-item\b", Opt);
|
||||
private static readonly Regex ChestText = new(@"<div\s+class=""text"">(.*?)</div>", Opt);
|
||||
private static readonly Regex ChestPoints = new(@"<div\s+class=""pt-chest"">\s*<b>\s*\+?\s*(\d+)\s*</b>.*?<b>\s*([^<]+?)\s*</b>", 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(@"<table[^>]*class=""[^""]*my-bidoo-table[^""]*""[^>]*>(.*?)</table>", Opt);
|
||||
private static readonly Regex Row = new(@"<tr\b[^>]*>(.*?)</tr>", Opt);
|
||||
private static readonly Regex MovementId = new(@"id=""data_mov(\d+)""", Opt);
|
||||
private static readonly Regex FirstRow = new(@"<span\s+class=""first_row_desc"">(.*?)</span>", Opt);
|
||||
private static readonly Regex SecondRow = new(@"<div\s+class=""second_row_desc[^""]*"">(.*?)</div>", Opt);
|
||||
private static readonly Regex Total = new(@"<td\s+class=""[^""]*\btot\b[^""]*"">(.*?)</td>", 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 ────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// I forzieri aperti: ogni <c>wrap-item</c> con il testo («Ottenuto tramite link il 9 Novembre 2026 alle 14:05»)
|
||||
/// e il premio (<c>pt-chest</c>, «+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.
|
||||
/// </summary>
|
||||
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<AccountReward>();
|
||||
var seen = new Dictionary<string, int>(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 ─────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// La cronologia crediti: una riga per movimento (<c>data_mov<id></c>), descrizione («3 Gratis»), totale
|
||||
/// («Gratis» o un prezzo). L'ora la scrive lo script della pagina: <c>'data_mov' + id … formattaDataStorico(unix</c>.
|
||||
/// </summary>
|
||||
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<string, long>(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<AccountReward>();
|
||||
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 ───────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// La campanella: <c>{"count":…, "elements": {…} | […]}</c>, ogni notifica con <c>id</c> e <c>content</c> in HTML.
|
||||
/// Si tengono solo gli indirizzi con <c>promocode</c>: poi passano dallo stesso controllo dei collegamenti della fonte.
|
||||
/// </summary>
|
||||
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 ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static string CompareToday(IEnumerable<AccountReward> 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();
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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<string, string> { ["value"] = "value - 'TelegramBotToken' - 'TelegramChatId'" }),
|
||||
|
||||
@@ -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);
|
||||
@@ -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)"
|
||||
|
||||
@@ -208,6 +208,12 @@ public sealed class AppSettings
|
||||
public int FreeBidsHoursStart { get; set; } = 8;
|
||||
public int FreeBidsHoursEnd { get; set; } = 24;
|
||||
|
||||
/// <summary>La campanella di Bidoo come seconda fonte di collegamenti (letta senza segnare le notifiche).</summary>
|
||||
public bool FreeBidsUseNotifications { get; set; } = true;
|
||||
|
||||
/// <summary>Ore fra una lettura delle ricompense (forzieri e cronologia crediti) e l'altra; 0 = mai.</summary>
|
||||
public int FreeBidsRewardsHours { get; set; } = 6;
|
||||
|
||||
/// <summary>Giro delle categorie per i forzieri: solo avviso, il bot non li apre.</summary>
|
||||
public bool ChestWatchEnabled { get; set; }
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<string, object?>
|
||||
{
|
||||
["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<string, object?>
|
||||
{
|
||||
["present"] = service != null,
|
||||
["counts"] = counts,
|
||||
["redemptions"] = redemptions,
|
||||
["chests"] = chests,
|
||||
["rewards"] = rewards,
|
||||
["log"] = service?.Lines(500).Select(l => new Dictionary<string, object?> { ["at"] = l.AtUtc, ["text"] = l.Text }).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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<string, object?> { ["at"] = l.AtUtc, ["text"] = l.Text }).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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']
|
||||
|
||||
@@ -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' } },
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"count":3,"elements":{"0":{"id":"9000003","users":"0","type":"9","arguments":"","created_at":"1795511000","visibleFor":"0","readFlag":"0","content":"<a href=\"https:\/\/it.bidoo.com\/?promocode=prova241126&sign=0123456789abcdef0123456789abcdef01234567\" target=\"_blank\"><p class=\"paragraph-notification\">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":"<a href=\"https:\/\/it.bidoo.com\/shop\/credits_history\" target=\"_blank\"><img class=\"wallet-icon\" src=\"https:\/\/static-cdn.bidoo.com\/res\/1.0\/images\/wallet.svg\">\n <p class=\"paragraph-notification\">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":"<p class=\"paragraph-notification\">Copia questo indirizzo: https:\/\/it.bidoo.com\/index.php?promocode=altro241126&sign=89abcdef0123456789abcdef0123456789abcdef<\/p>"}},"audio":"","exceed":22,"shexc":22,"t":1795541810}
|
||||
@@ -0,0 +1,42 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- Copia ridotta della struttura di /bids_history.php (24/11/2026), valori inventati: nessun dato personale. -->
|
||||
<html lang="it">
|
||||
<head><title>My Bidoo - Cronologia Crediti - Bidoo</title></head>
|
||||
<body>
|
||||
<table class="table table-striped my-bidoo-table">
|
||||
<thead><tr><th>Data</th><th>Descrizione</th><th>Prezzo</th><th class="hidden-xs">Metodo di Pagamento</th></tr></thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td class="date"> <div id="data_mov1000000003" class="text-dark menu_my_datime_box"></div> <div id="ora_mov1000000003" class="menu_my_datime_box"></div> </td>
|
||||
<td class="text-dark desc"> <div class="descr"><span class="first_row_desc">5 <i class="bi bi-single-money"></i> Gratis</span><div class="second_row_desc truncate_text"> </div> <span class="isGainedWithBonus"></span> </div> </td>
|
||||
<td class="text-dark tot"><b class="text-green">Gratis</b></td>
|
||||
<td class="hidden-xs"><b class="text-green">Gratis</b></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="date"> <div id="data_mov1000000002" class="text-dark menu_my_datime_box"></div> <div id="ora_mov1000000002" class="menu_my_datime_box"></div> </td>
|
||||
<td class="text-dark desc"> <div class="descr"><span class="first_row_desc">2 <i class="bi bi-single-money"></i> Gratis</span><div class="second_row_desc truncate_text"> </div> <span class="isGainedWithBonus"></span> </div> </td>
|
||||
<td class="text-dark tot"><b class="text-green">Gratis</b></td>
|
||||
<td class="hidden-xs"><b class="text-green">Gratis</b></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="date"> <div id="data_mov1000000001" class="text-dark menu_my_datime_box"></div> <div id="ora_mov1000000001" class="menu_my_datime_box"></div> </td>
|
||||
<td class="text-dark desc"> <div class="descr"><span class="first_row_desc">1.000 <i class="bi bi-single-money"></i> Puntate</span><div class="second_row_desc truncate_text"> Pacchetto </div> <span class="isGainedWithBonus"></span> </div> </td>
|
||||
<td class="text-dark tot"><b>100,00 €</b></td>
|
||||
<td class="hidden-xs"><b>Carta</b></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="date"> <div id="data_mov1000000000" class="text-dark menu_my_datime_box"></div> </td>
|
||||
<td class="text-dark desc"> <div class="descr"><span class="first_row_desc">3 <i class="bi bi-single-money"></i> Gratis</span></div> </td>
|
||||
<td class="text-dark tot"><b class="text-green">Gratis</b></td>
|
||||
<td class="hidden-xs"><b class="text-green">Gratis</b></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination-wrap"><a class="pagination_active" href="/bids_history.php?page=1">1</a> <a class="pagination" href="/bids_history.php?page=2">2</a></div>
|
||||
<script>
|
||||
if (MM_findObj('data_mov' + 1000000003)) { sIDdatemov = 'data_mov' + 1000000003; msIDdatemov = 'mdata_mov' + 1000000003; sValuedatemov = formattaDataStorico(1795511512, 'it'); $('#'+sIDdatemov).html(sValuedatemov); $('#'+msIDdatemov).html('<b>'+sValuedatemov+'</b>'); } if (MM_findObj('ora_mov' + 1000000003)) { sIDoramov = 'ora_mov' + 1000000003; sValueoramov = formattaOraStorico(1795511512); }
|
||||
if (MM_findObj('data_mov' + 1000000002)) { sIDdatemov = 'data_mov' + 1000000002; msIDdatemov = 'mdata_mov' + 1000000002; sValuedatemov = formattaDataStorico(1795473185, 'it'); $('#'+sIDdatemov).html(sValuedatemov); } if (MM_findObj('ora_mov' + 1000000002)) { sValueoramov = formattaOraStorico(1795473185); }
|
||||
if (MM_findObj('data_mov' + 1000000001)) { sIDdatemov = 'data_mov' + 1000000001; msIDdatemov = 'mdata_mov' + 1000000001; sValuedatemov = formattaDataStorico(1790000000, 'it'); $('#'+sIDdatemov).html(sValuedatemov); }
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,49 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- Copia ridotta della struttura di /my_chests.php (24/11/2026), valori inventati: nessun dato personale. -->
|
||||
<html lang="it">
|
||||
<head><title>My Bidoo - Le mie ricompense - Bidoo</title></head>
|
||||
<body data-lang="it" class="page-award">
|
||||
<div class="wrap-bonus-section">
|
||||
<a href="javascript:void(0)" class="chest-opened-collapse"> <div class="title-award">Cronologia <i class="fa fa-angle-down " aria-hidden="true"></i></div> </a>
|
||||
<div class="wrap-items-opened collapse">
|
||||
<div class="items-sections-opened">
|
||||
<div class="wrap-item " data-is_expire="1" data-is_opened="1">
|
||||
<div class="pt5"> <img src="https://static-cdn.bidoo.com/res/1.0/images/chest_opened_static.png" class="img-chest"> </div>
|
||||
<div class="pt5">
|
||||
<div class="text">Ottenuto tramite link il 24 Novembre 2026 alle 09:05</div>
|
||||
<div class="pt-chest"><b>+5</b> <img src="https://static-cdn.bidoo.com/res/1.0/images/bids1.svg" class="coin"> <b>Puntate</b></div>
|
||||
<!-- <div class="used">--><!--</div>-->
|
||||
</div>
|
||||
</div>
|
||||
<div class="wrap-item " data-is_expire="1" data-is_opened="1">
|
||||
<div class="pt5"> <img src="https://static-cdn.bidoo.com/res/1.0/images/chest_opened_static.png" class="img-chest"> </div>
|
||||
<div class="pt5">
|
||||
<div class="text">Ottenuto tramite link il 24 Novembre 2026 alle 09:05</div>
|
||||
<div class="pt-chest"><b>+5</b> <img src="https://static-cdn.bidoo.com/res/1.0/images/bids1.svg" class="coin"> <b>Puntate</b></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wrap-item " data-is_expire="1" data-is_opened="1">
|
||||
<div class="pt5"> <img src="https://static-cdn.bidoo.com/res/1.0/images/chest_opened_static.png" class="img-chest"> </div>
|
||||
<div class="pt5">
|
||||
<div class="text">Ottenuto tramite link il 23 Novembre 2026 alle 21:40</div>
|
||||
<div class="pt-chest"><b>+2</b> <img src="https://static-cdn.bidoo.com/res/1.0/images/bids1.svg" class="coin"> <b>Puntate</b></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wrap-item " data-is_expire="1" data-is_opened="1">
|
||||
<div class="pt5"> <img src="https://static-cdn.bidoo.com/res/1.0/images/chest_opened_static.png" class="img-chest"> </div>
|
||||
<div class="pt5">
|
||||
<div class="text">Ottenuto tramite aste di puntate confermate il 3 Novembre 2026 alle 18:12</div>
|
||||
<div class="pt-chest"><b>+15</b> <img src="https://static-cdn.bidoo.com/res/1.0/images/bids1.svg" class="coin"> <b>Puntate</b></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wrap-item " data-is_expire="1">
|
||||
<div class="pt5"> <img src="https://static-cdn.bidoo.com/res/1.0/images/chest_closed_static.png" class="img-chest"> </div>
|
||||
<div class="pt5">
|
||||
<div class="text">Dal forziere del 2 Novembre 2026 10:30</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,99 @@
|
||||
using Mimante.Bidoo;
|
||||
using Mimante.Bidoo.FreeBids;
|
||||
using Xunit;
|
||||
|
||||
namespace Mimante.Tests;
|
||||
|
||||
/// <summary>Ricompense, cronologia crediti e campanella di Bidoo (#38): copie della struttura vera, valori inventati.</summary>
|
||||
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 = "<html><body><form action=\"/login.php\"><input name=\"password\"></form></body></html>";
|
||||
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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user