Riscatto delle puntate gratuite e avviso dei forzieri, con la pagina Puntate gratis (#27)
verifica / controlli (push) Successful in 55s
verifica / prove (push) Successful in 2m53s
verifica / immagine (push) Failing after 12m47s

Alberto ha chiesto di riavere il riscatto automatico, escluso dalla specifica perché nella versione
desktop era inaffidabile. Il 24/11 la sequenza è stata misurata dal vivo: prima la pagina del codice
con la sessione, poi una sola push_promotions.php come AJAX; il secondo passo da solo o ripetuto dà 400.

- Bidoo/FreeBids: lettura della fonte di puntateaste.it (PromoFeed), controllo stretto dei
  collegamenti (PromoLinkCheck), grammatica degli esiti (PromoResponse), scelta di cosa aprire dentro
  i tetti (RedeemPlanner) e il servizio di fondo con pausa automatica, registro in memoria e su file
  riscatti-AAAA-MM-GG.log, avvisi Telegram.
- BidooApi.RedeemPromoAsync fa i due passi come coppia, di fondo, senza seguire redirezioni e senza
  CheckSession (un 403 su un codice falso non scade la sessione). Net/ExternalHttp non manda mai il
  cookie di Bidoo alla fonte esterna.
- Prudenza: spento di fabbrica, uno per giro finché il primo accredito non si vede nel saldo, tetti
  per giro e per giorno, pause casuali, ore scelte, pausa su showVerify e warningOrigin.
- Forzieri solo segnalati: giro delle categorie, una riga per giorno e categoria, Telegram.
- Migrazione 0005 (promo_redemptions, chests), riferimenti nella sezione freeBids di bidoo.json,
  impostazioni nuove, pagina «Puntate gratis» con riscattate, forzieri e registro.
- Prove: fonte, collegamenti, esiti, scelta, sequenza dei due passi con un Bidoo finto che risponde
  400 senza il primo passo, nessun cookie verso la fonte, forzieri, ore e riferimenti di fabbrica.
- ADR 0015; architettura, CHANGELOG e stato. Ricompense e campanella rimandate alla #38; il primo
  riscatto dal bot va ancora fatto dal vivo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-24 13:27:08 +01:00
1 parent 5646391820
commit eb2d7c6ff7
31 files changed
+1876 -6

No files matched your search

+6
View File
@@ -32,6 +32,12 @@ copia nella release la sezione della versione.
puntato. Ogni mia puntata ha i millisecondi alla scadenza al verdetto, all'invio e alla risposta, lo
stato HTTP, la risposta di Bidoo e le letture intorno; una puntata decisa e non partita dice perché.
Le decisioni hanno l'ora in cui sono state prese, e ogni asta chiusa conta le sue decisioni.
- **Puntate gratis** (pagina nuova, ADR 0015, migrazione 0005): il bot riscatta da solo i codici
gratuiti pubblicati ogni giorno, con i due passi che Bidoo vuole, e tiene l'elenco delle puntate
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.
## 1.2.0
@@ -0,0 +1,54 @@
# 0015 — Riscatto delle puntate gratuite e avviso dei forzieri
**Stato:** accettata (2.0.0, 24/11/2026)
## Contesto
La specifica (§4.3) escludeva il riscatto delle puntate gratuite: nella versione desktop era
inaffidabile e il codice era rimasto come riferimento non compilato fino alla 1.2.0. Alberto lo ha
chiesto di nuovo, con una pagina propria per le puntate riscattate, i forzieri e il registro delle
operazioni. Il 24/11/2026 la sequenza è stata provata dal vivo con l'accesso vero:
- serve **aprire prima il collegamento** `/?promocode=X&sign=Y` come pagina (senza `X-Requested-With`),
con la sessione; poi **una sola** `GET /push_promotions.php?code=X&sign=Y&kp=&by=` come AJAX;
- il secondo passo da solo, o ripetuto, risponde `400`; un codice falso `403`; senza sessione `401`;
- le risposte sono testo: `ok-<saldo>`, `warningOrigin-<saldo>-<base64>`, `expired-<unix>`, `clicked`,
`no`, `showVerify`.
I collegamenti si trovano su puntateaste.it (`POST /index.php`, `s=1&l=<mezzanotte di Roma>`, JSON), che
non richiede accesso. Le notifiche di Bidoo con le puntate sono push del browser, non ricevibili dal
server. I forzieri si vedono con `get_chest_tag_url.php?tag=N` per categoria.
## Decisione
- **Spento di fabbrica** (`FreeBidsEnabled`, `ChestWatchEnabled`): si accende dalla pagina «Puntate
gratis». Solo sul sito vero e con utente collegato e sessione valida: il simulatore non crea il servizio.
- **I due passi sono una coppia indivisibile** (`BidooApi.RedeemPromoAsync`): priorità di fondo, mai sulla
corsia delle puntate, senza seguire redirezioni, e senza passare da `CheckSession`: un `403` su un codice
falso non deve far risultare scaduta la sessione. Un esito `400` non è definitivo: il codice si riprova
in un giro successivo, fino a `FreeBidsMaxAttempts`.
- **La fonte esterna non riceve mai il cookie di Bidoo**: `Net/ExternalHttp` è un client separato, senza
contenitore dei cookie per costruzione.
- **Si apre solo ciò che si riconosce** (`PromoLinkCheck`): https, l'host di `BaseUrl`, la porta
predefinita, uno dei percorsi ammessi, soltanto `promocode` e `sign` validi (più `kp` e `by`); niente
accorciatori, niente frammenti, l'indirizzo firmato resta intatto.
- **Prudenza**: un solo collegamento per giro finché il primo `ok-` non è confermato dal saldo; pausa
automatica (con avviso) su `showVerify`, `warningOrigin`, sessione mancante o risposta sconosciuta, tolta
solo a mano; tetti per giro e per giorno, pause casuali fra un collegamento e l'altro, giro con un
intervallo e uno scarto casuale, solo nelle ore scelte.
- **Forzieri: solo avviso.** Il bot gira le categorie, registra un forziere per giorno e categoria e lo
annuncia su Telegram con l'indirizzo; non lo apre.
- **Tutto ciò che è un fatto del sito** (indirizzi, corpo della richiesta, percorsi, parametri, prefissi
degli esiti, categorie dei forzieri) sta nella sezione `freeBids` di `bidoo.json`: si corregge senza
rilascio.
- **Storico**: `promo_redemptions` (ogni tentativo con esito, saldo prima e dopo, risposta grezza) e
`chests` (migrazione 0005); registro delle operazioni in memoria e su `riscatti-AAAA-MM-GG.log`.
## 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.
- Il primo riscatto dal bot va fatto dal vivo, con Alberto, e la risposta registrata va confrontata con
il saldo prima di lasciarlo acceso.
+23
View File
@@ -289,6 +289,8 @@ un secondo pool con tempo massimo di 15 s.
| `products` | Le schede dell'utente: paletti scritti (prezzo minimo dalla migrazione 0002, massimo, puntate), valore reale, seguito, orizzonte, modo delle aste aggiunte. |
| `watched_products` | Le aste già proposte o tolte per ogni prodotto seguito: la sorveglianza non le ripropone. |
| `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. |
`bids`, `resets` e `bot_decisions` sono partizionate per mese su `created_at`; la partizione del mese
dopo nasce il giorno 25 e all'avvio.
@@ -326,6 +328,27 @@ Lo strumento da riga di comando legge l'archivio su una connessione propria in s
i file definitivi (più vecchi di due giorni), `verifica --contro-db` riconta con lo stesso filtro.
- Velocità limitata (20 MB/s), pausa dalle 4:20 alle 5:40 (manutenzione del bot), riserva di spazio libero.
### Puntate gratuite e forzieri (`Bidoo/FreeBids`, ADR 0015)
`FreeBidsService` nasce solo nel mondo vero (`BotWorld.BuildAsync`) e ha due lavori di fondo:
- **Riscatto** (`RunAsync`, spento di fabbrica): a ogni giro legge con `Net/ExternalHttp` (senza cookie)
i collegamenti di oggi e di ieri dalla fonte di `freeBids.feedUrl` (`PromoFeed`), scarta quelli che
`PromoLinkCheck` non riconosce, legge da `promo_redemptions` i codici già chiusi o tentati troppe volte
e quanti accrediti ci sono oggi, e lascia scegliere a `RedeemPlanner` (prima i veloci, poi i più
recenti, dentro i tetti; uno solo finché il primo accredito non è confermato dal saldo). Ogni
collegamento passa da `BidooApi.RedeemPromoAsync` (pagina del codice, poi `push_promotions.php`), la
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.
- **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.
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`,
`freebids.redeem` (un collegamento incollato) e `freebids.resume`. Gli interruttori passano da
`settings.save`.
### Impostazioni dal vivo e dal riavvio (`Settings/SettingsStore`)
Il motore rilegge `SettingsStore.Current` a ogni ciclo, e `Bot.OnSettingsChanged` riapplica a ogni
+6
View File
@@ -172,6 +172,8 @@ Chromium con i fotogrammi, spegnimento ordinato) e pubblicata come `alby96/miman
9. **Statistiche dei prodotti salvate prima della 1.2.0**: la chiusura mediana per ora
(`MedianCloseByHourBand`) ha le fasce vecchie e le statistiche nuove sono vuote finché il prodotto non
chiude un'asta; dopo l'aggiornamento conviene premere «Ricalcola statistiche» una volta.
10. **Primo riscatto dal bot (2.0.0)**: con la sessione vera, «Esegui ora» o un collegamento incollato;
controllare nella scheda Registro risposta e saldo prima e dopo, poi accendere il riscatto automatico.
## Decisioni prese (domande D2–D14)
@@ -244,6 +246,10 @@ cambiarle; dove serve, il punto nel codice è indicato.
all'avvio) e il messaggio dopo il salvataggio lo dice. Nessun segno fisso accanto ai campi.
- **Esito delle decisioni NO-OP**: «risposto_da» nel CSV dei dati è chi ha puntato subito dopo il prezzo
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.
## Cosa è rimasto della versione desktop dopo la rimozione di `legacy/` (1.1.0)
+79
View File
@@ -0,0 +1,79 @@
using System.Globalization;
using System.Text.Json;
using Mimante.Bidoo.FreeBids;
using Mimante.Net;
namespace Mimante.Bidoo;
/// <summary>Un riscatto: l'esito del secondo passo e lo stato HTTP del primo.</summary>
public sealed record RedeemAttempt(RedeemResult Result, int PageStatus, int LatencyMs);
/// <summary>Un giro su una categoria dei forzieri: <paramref name="Ok"/> falso se la risposta non si è letta.</summary>
public sealed record ChestProbe(bool Ok, string? Url, string? Error);
public sealed partial class BidooApi
{
/// <summary>
/// Il riscatto di un collegamento promozionale, i due passi come coppia indivisibile e nell'ordine giusto:
/// (1) la pagina del codice, come documento, con la sessione e senza <c>X-Requested-With</c> (con l'intestazione
/// AJAX Bidoo risponde 200 senza accreditare); (2) una sola GET di <c>push_promotions.php</c>, che dà l'esito.
/// Il secondo passo da solo o ripetuto dà 400. Priorità di fondo, mai sulla corsia delle puntate, nessuna
/// redirezione seguita. Non passa da <c>CheckSession</c>: un 403 su un codice falso non è una sessione scaduta.
/// </summary>
public async Task<RedeemAttempt> RedeemPromoAsync(PromoLink link, CancellationToken ct)
{
var refs = _refs();
var fb = refs.FreeBids;
var home = refs.BaseUrl.TrimEnd('/') + "/";
var page = await _transport.SendAsync(_transport.BuildGet(link.Url.OriginalString, home, ajax: false),
RequestPriority.Background, ct, followRedirects: false).ConfigureAwait(false);
if (page.IsNetworkError)
return new RedeemAttempt(PromoResponse.Parse(null, page.Error, fb.Grammar), 0, page.LatencyMs);
if (page.StatusCode is 401 || (page.Success && DataResponseParser.LooksLikeLoginPage(page.Body, refs)))
return new RedeemAttempt(PromoResponse.Parse(401, "", fb.Grammar), page.StatusCode, page.LatencyMs);
if (page.StatusCode is >= 400)
return new RedeemAttempt(PromoResponse.Parse(page.StatusCode, Short(page.Body), fb.Grammar), page.StatusCode, page.LatencyMs);
var url = refs.Url(fb.Redeem, ("code", Uri.EscapeDataString(link.Code)), ("sign", Uri.EscapeDataString(link.Sign)));
var answer = await _transport.SendAsync(_transport.BuildGet(url, link.Url.OriginalString, ajax: true),
RequestPriority.Background, ct, followRedirects: false).ConfigureAwait(false);
var status = answer.IsNetworkError ? (int?)null : answer.StatusCode;
return new RedeemAttempt(PromoResponse.Parse(status, answer.IsNetworkError ? answer.Error : answer.Body, fb.Grammar),
page.StatusCode, page.LatencyMs + answer.LatencyMs);
}
/// <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)
{
var refs = _refs();
var outcome = await _transport.SendAsync(
_transport.BuildGet(refs.Url(refs.FreeBids.ChestTag, ("tag", tag.ToString(CultureInfo.InvariantCulture)))),
RequestPriority.Background, ct, followRedirects: false).ConfigureAwait(false);
if (!outcome.Success) return new ChestProbe(false, null, outcome.Describe());
return ParseChest(outcome.Body);
}
/// <summary>La risposta di <c>get_chest_tag_url.php</c>. Pura.</summary>
public static ChestProbe ParseChest(string? body)
{
try
{
using var doc = JsonDocument.Parse(string.IsNullOrWhiteSpace(body) ? "null" : body);
if (doc.RootElement.ValueKind != JsonValueKind.Object || !doc.RootElement.TryGetProperty("url", out var u))
return new ChestProbe(false, null, "risposta senza url: il formato è cambiato?");
return u.ValueKind switch
{
JsonValueKind.Null => new ChestProbe(true, null, null),
JsonValueKind.String when string.IsNullOrWhiteSpace(u.GetString()) => new ChestProbe(true, null, null),
JsonValueKind.String => new ChestProbe(true, u.GetString()!.Trim(), null),
_ => new ChestProbe(false, null, "url di tipo inatteso")
};
}
catch (JsonException)
{
return new ChestProbe(false, null, "la risposta non è JSON");
}
}
private static string Short(string? s) => s is null ? "" : s.Length > 300 ? s[..300] : s;
}
+1 -1
View File
@@ -23,7 +23,7 @@ public sealed record BidAttempt(
/// Gli indirizzi vengono tutti dai riferimenti. Una risposta 403 o la pagina di login al
/// posto dei dati significano sessione non valida: lo si dice con <see cref="SessionInvalid"/>.
/// </summary>
public sealed class BidooApi
public sealed partial class BidooApi
{
private readonly BidooTransport _transport;
private readonly BidLane _lane;
+19
View File
@@ -24,6 +24,25 @@ public sealed class BidooReferences
public TimingSet Timing { get; set; } = new();
public LimitSet Limits { get; set; } = new();
public ParsingSet Parsing { get; set; } = new();
public FreeBidsSet FreeBids { get; set; } = new();
/// <summary>Il riscatto delle puntate gratuite e i forzieri (<c>Bidoo/FreeBids</c>).</summary>
public sealed class FreeBidsSet
{
public string FeedUrl { get; set; } = "";
public string FeedBody { get; set; } = "";
public string FeedReferer { get; set; } = "";
public List<string> PromoPaths { get; set; } = new();
public List<string> PromoExtraParameters { get; set; } = new();
public string Redeem { get; set; } = "";
public global::Mimante.Bidoo.FreeBids.RedeemGrammar Grammar { get; set; } = new();
public string ChestTag { get; set; } = "";
public List<int> ChestTags { get; set; } = new();
public string RewardsPage { get; set; } = "";
}
/// <summary>L'host di Bidoo (da <see cref="BaseUrl"/>): l'unico su cui si apre un collegamento promozionale.</summary>
public string Host => Uri.TryCreate(BaseUrl, UriKind.Absolute, out var u) ? u.Host : "";
public sealed class EndpointSet
{
@@ -0,0 +1,398 @@
using System.Globalization;
using System.Text.Json;
using Mimante.Data;
using Mimante.Logging;
using Mimante.Net;
using Mimante.Session;
using Mimante.Settings;
using Mimante.Telegram;
namespace Mimante.Bidoo.FreeBids;
/// <summary>
/// Il riscatto automatico delle puntate gratuite e il giro dei forzieri (ADR 0015). Solo nel mondo vero e solo
/// con l'utente di Bidoo collegato; mai nel simulatore. Prudente per costruzione: spento di fabbrica, un solo
/// collegamento per giro finché il primo accredito non è confermato dal saldo, pausa da sola su un esito che
/// chiede attenzione (verifica, avviso sulla provenienza, risposta sconosciuta, sessione assente), tetti per
/// giro e per giorno, pause casuali, solo nelle ore scelte, nessun nuovo tentativo dentro lo stesso giro.
/// I forzieri si rilevano, si registrano e si avvisano: non si aprono.
/// </summary>
public sealed class FreeBidsService : IDisposable
{
public const string StateKey = "freebids/state";
public const string LogKind = "riscatti";
private const string Tag = "PUNTATE GRATIS";
/// <summary>Lo stato che sopravvive al riavvio (documento <see cref="StateKey"/>).</summary>
public sealed class State
{
public bool Confirmed { get; set; }
public bool Paused { get; set; }
public string? PauseReason { get; set; }
public DateTime? PausedAtUtc { get; set; }
}
/// <summary>Una riga del registro delle operazioni.</summary>
public sealed record LogLine(DateTime AtUtc, string Text);
/// <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);
private readonly BidooApi _api;
private readonly ExternalHttp _external;
private readonly Func<BidooReferences> _refs;
private readonly Func<AppSettings> _settings;
private readonly AccountState _account;
private readonly IDocumentStore _documents;
private readonly WriteQueue _queue;
private readonly Db _db;
private readonly AppLog _log;
private readonly FileLog? _file;
private readonly TelegramNotifier? _telegram;
private readonly Func<bool> _canRedeem;
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly LinkedList<LogLine> _lines = new();
private readonly object _sync = new();
private readonly Random _rng = new();
private readonly HashSet<string> _chestsSeen = new(StringComparer.Ordinal);
private State _state;
private volatile bool _running;
private DateTime? _lastRunUtc, _nextRunUtc, _lastChestUtc;
private string? _lastSummary;
private DateOnly _chestDay;
public FreeBidsService(BidooApi api, Func<BidooReferences> refs, Func<AppSettings> settings, AccountState account,
IDocumentStore documents, WriteQueue queue, Db db, AppLog log, FileLog? file, TelegramNotifier? telegram, Func<bool> canRedeem,
ExternalHttp? external = null)
{
_api = api;
_refs = refs;
_settings = settings;
_account = account;
_documents = documents;
_queue = queue;
_db = db;
_log = log;
_file = file;
_telegram = telegram;
_canRedeem = canRedeem;
_external = external ?? new ExternalHttp();
_state = LoadState(documents);
}
/// <summary>Cambia a ogni riga del registro o cambio di stato: l'interfaccia ridisegna solo allora.</summary>
public int Version { get; private set; }
public IReadOnlyList<LogLine> Lines(int max = 300)
{
lock (_sync) return _lines.Take(max).ToList();
}
public Status Current()
{
var s = _settings();
var available = _canRedeem();
int chests;
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);
}
/// <summary>Toglie la pausa (dalla pagina): il prossimo giro riparte con un collegamento solo, finché il saldo non conferma.</summary>
public void Resume()
{
_state.Paused = false;
_state.PauseReason = null;
_state.PausedAtUtc = null;
_state.Confirmed = false;
SaveState();
Note("pausa tolta dall'utente: il prossimo giro apre un collegamento solo finché il saldo non conferma");
}
/// <summary>Il ciclo dei riscatti: primo giro dopo un minuto (la sessione deve essere verificata), poi a intervalli.</summary>
public Task RunAsync(CancellationToken ct) => Task.Run(async () =>
{
if (!await DelayAsync(TimeSpan.FromSeconds(60), ct).ConfigureAwait(false)) return;
while (!ct.IsCancellationRequested)
{
var s = _settings();
if (s.FreeBidsEnabled && InHours(s, AppInfo.LocalNow.Hour))
{
try { await RunOnceAsync(manual: false, ct).ConfigureAwait(false); }
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
catch (Exception ex) { Note($"giro non riuscito: {ex.Message}", warn: true); }
}
var wait = TimeSpan.FromMinutes(s.FreeBidsIntervalMinutes) + TimeSpan.FromSeconds(_rng.Next(0, 121));
_nextRunUtc = DateTime.UtcNow + wait;
Bump();
if (!await DelayAsync(wait, ct).ConfigureAwait(false)) return;
}
}, ct);
/// <summary>Il giro dei forzieri, a intervalli, se acceso.</summary>
public Task RunChestsAsync(CancellationToken ct) => Task.Run(async () =>
{
if (!await DelayAsync(TimeSpan.FromSeconds(90), ct).ConfigureAwait(false)) return;
while (!ct.IsCancellationRequested)
{
var s = _settings();
if (s.ChestWatchEnabled)
{
try { await ScanChestsAsync(ct).ConfigureAwait(false); }
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
catch (Exception ex) { Note($"giro dei forzieri non riuscito: {ex.Message}", warn: true); }
}
if (!await DelayAsync(TimeSpan.FromMinutes(s.ChestWatchMinutes) + TimeSpan.FromSeconds(_rng.Next(0, 61)), ct).ConfigureAwait(false)) return;
}
}, ct);
public static bool InHours(AppSettings s, int hour) =>
s.FreeBidsHoursStart == s.FreeBidsHoursEnd
|| (s.FreeBidsHoursStart < s.FreeBidsHoursEnd
? hour >= s.FreeBidsHoursStart && hour < s.FreeBidsHoursEnd
: hour >= s.FreeBidsHoursStart || hour < s.FreeBidsHoursEnd);
/// <summary>Un giro: legge la fonte (oggi e ieri), sceglie, riscatta. <paramref name="manual"/>: «Esegui ora» (vale anche spento).</summary>
public async Task<string> RunOnceAsync(bool manual, CancellationToken ct)
{
if (!_canRedeem()) return Done("nessun giro: serve l'utente di Bidoo collegato");
if (!await _gate.WaitAsync(0, ct).ConfigureAwait(false)) return "un giro è già in corso";
_running = true;
Bump();
try
{
var refs = _refs();
var fb = refs.FreeBids;
var candidates = new List<RedeemCandidate>();
var rejected = 0;
var today = DateOnly.FromDateTime(AppInfo.LocalNow);
foreach (var day in new[] { today, today.AddDays(-1) })
{
var answer = await _external.PostFormAsync(fb.FeedUrl, PromoFeed.Body(fb.FeedBody, day, AppInfo.TimeZone), fb.FeedReferer,
refs.EffectiveUserAgent(""), ct).ConfigureAwait(false);
if (!answer.Success) { Note($"fonte non raggiunta ({answer.Describe()})", warn: true); continue; }
var feed = PromoFeed.Parse(answer.Body);
if (feed.Error != null) { Note($"fonte: {feed.Error}", warn: true); continue; }
foreach (var item in feed.Items)
{
var v = PromoLinkCheck.Check(item.Link, refs.Host, fb.PromoPaths, fb.PromoExtraParameters);
if (v.Ok) candidates.Add(new RedeemCandidate(v.Link!, "puntateaste", item.Points, item.Fast, item.AddedUnix));
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),
await CreditedTodayAsync(ct).ConfigureAwait(false), _state.Confirmed, _state.Paused);
var head = $"{(manual ? "giro a mano" : "giro")}: {candidates.Count} collegamenti validi" + (rejected > 0 ? $", {rejected} scartati" : "") + $"; {plan.Why}";
if (plan.Open.Count == 0) return Done(head);
Note(head);
var credited = 0;
var gained = 0;
for (var i = 0; i < plan.Open.Count; i++)
{
if (i > 0)
{
var pause = TimeSpan.FromSeconds(_rng.Next(s.FreeBidsPauseMinSeconds, s.FreeBidsPauseMaxSeconds + 1));
await Task.Delay(pause, ct).ConfigureAwait(false);
}
var r = await RedeemOneAsync(plan.Open[i], manual: false, ct).ConfigureAwait(false);
if (r.Result.Outcome is RedeemOutcome.Credited or RedeemOutcome.CreditedWithWarning) { credited++; gained += r.Gained ?? 0; }
if (_state.Paused) break;
}
return Done($"giro finito: {credited} riscatti riusciti, {gained} puntate in più");
}
finally
{
_running = false;
_lastRunUtc = DateTime.UtcNow;
_gate.Release();
Bump();
}
}
/// <summary>Un collegamento incollato dalla pagina: lo stesso controllo, un solo tentativo, anche a riscatto spento o in pausa.</summary>
public async Task<string> RedeemPastedAsync(string text, CancellationToken ct)
{
if (!_canRedeem()) return "serve l'utente di Bidoo collegato";
var refs = _refs();
var v = PromoLinkCheck.Check(text, refs.Host, refs.FreeBids.PromoPaths, refs.FreeBids.PromoExtraParameters);
if (!v.Ok) { Note($"collegamento incollato scartato: {v.Reason}"); return $"Collegamento non valido: {v.Reason}."; }
var known = await KnownAsync(new[] { v.Link!.Code }, ct).ConfigureAwait(false);
if (known.TryGetValue(v.Link.Code, out var k) && k.Final) return $"Il codice {v.Link.Code} è già stato usato.";
if (!await _gate.WaitAsync(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false)) return "un giro è in corso: riprova fra poco";
try
{
var r = await RedeemOneAsync(new RedeemCandidate(v.Link, "incollato", 0, false, 0), manual: true, ct).ConfigureAwait(false);
return $"{v.Link.Code}: {r.Result.Describe()}" + (r.Gained is > 0 ? $", +{r.Gained} puntate" : "") + ".";
}
finally
{
_gate.Release();
Bump();
}
}
private sealed record Done1(RedeemResult Result, int? Gained);
private async Task<Done1> RedeemOneAsync(RedeemCandidate c, bool manual, CancellationToken ct)
{
var before = _account.Total;
var attempt = await _api.RedeemPromoAsync(c.Link, ct).ConfigureAwait(false);
var r = attempt.Result;
int? gained = r.Balance is { } after && before is { } b ? after - b : null;
if (r.Balance is { } balance) _account.SetTotal(balance);
// Il primo accredito conta solo se il saldo lo conferma: allora si passa a più collegamenti per giro.
if (r.Outcome == RedeemOutcome.Credited && gained is > 0 && !_state.Confirmed)
{
_state.Confirmed = true;
SaveState();
Note($"primo accredito confermato dal saldo ({before} -> {r.Balance}): da ora fino a {_settings().FreeBidsMaxPerRun} collegamenti per giro");
}
_queue.Enqueue(
"INSERT INTO promo_redemptions(code, source, source_id, link, points_declared, outcome, balance_before, balance_after, gained, " +
" page_status, response, note, latency_ms, manual) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)",
c.Link.Code, c.Source, null, c.Link.Url.OriginalString, c.Points > 0 ? c.Points : null, OutcomeCode(r.Outcome), before, r.Balance,
gained, attempt.PageStatus, LogText.Clean(r.Raw.Length > 500 ? r.Raw[..500] : r.Raw), r.Warning, attempt.LatencyMs, manual);
var text = $"{c.Link.Code} ({c.Source}{(c.Points > 0 ? $", {c.Points} dichiarate" : "")}): {r.Describe()}" + (gained is { } g ? $", {g:+0;-0;0} puntate" : "");
Note(text, warn: r.Pause);
if (r.Outcome is RedeemOutcome.Credited or RedeemOutcome.CreditedWithWarning && _settings().TelegramNotifyFreeBids)
_telegram?.Enqueue(TelegramFormat.Message("Puntate gratis", text));
if (r.Pause)
{
_state.Paused = true;
_state.PauseReason = r.Describe();
_state.PausedAtUtc = DateTime.UtcNow;
SaveState();
Note($"riscatto automatico in pausa: {r.Describe()}. Guarda la pagina «Puntate gratis» e togli la pausa quando è tutto a posto", warn: true);
if (_settings().TelegramNotifyFreeBids)
_telegram?.Enqueue(TelegramFormat.Message("Puntate gratis in pausa", r.Describe()));
}
return new Done1(r, gained);
}
private async Task ScanChestsAsync(CancellationToken ct)
{
var refs = _refs();
var day = DateOnly.FromDateTime(AppInfo.LocalNow);
lock (_sync)
{
if (day != _chestDay) { _chestsSeen.Clear(); _chestDay = day; }
}
var errors = 0;
foreach (var tag in refs.FreeBids.ChestTags)
{
var probe = await _api.ProbeChestAsync(tag, ct).ConfigureAwait(false);
if (!probe.Ok) errors++;
else if (probe.Url is { } url)
{
bool fresh;
lock (_sync) fresh = _chestsSeen.Add($"{tag}|{url}");
_queue.Enqueue(
"INSERT INTO chests(tag, url, day) VALUES($1, $2, $3) ON CONFLICT (tag, url, day) DO UPDATE SET last_seen = now()",
tag, url, day.ToDateTime(TimeOnly.MinValue));
if (fresh)
{
Note($"forziere nella categoria {tag}: {url}");
if (_settings().TelegramNotifyFreeBids)
_telegram?.Enqueue(TelegramFormat.Message("Forziere su Bidoo", $"Categoria {tag}: {url}"));
}
}
await Task.Delay(400 + _rng.Next(0, 400), ct).ConfigureAwait(false);
}
if (errors > 0) Note($"forzieri: {errors} categorie senza risposta leggibile", warn: errors == refs.FreeBids.ChestTags.Count);
_lastChestUtc = DateTime.UtcNow;
Bump();
}
/// <summary>Che cosa si sa dei codici dallo storico: tentativi ed esito definitivo.</summary>
private async Task<Dictionary<string, KnownCode>> KnownAsync(string[] codes, CancellationToken ct)
{
if (codes.Length == 0) return new Dictionary<string, KnownCode>(StringComparer.Ordinal);
ct.ThrowIfCancellationRequested();
var rows = await _db.QueryAsync(
"SELECT code, count(*)::int AS n, bool_or(outcome = ANY($2)) AS final FROM promo_redemptions WHERE code = ANY($1) GROUP BY code",
r => (Code: r.Str("code"), N: r.Int("n"), Final: r.BoolOrNull("final") ?? false), codes, FinalCodes).ConfigureAwait(false);
return rows.ToDictionary(x => x.Code, x => new KnownCode(x.N, x.Final), StringComparer.Ordinal);
}
private async Task<int> CreditedTodayAsync(CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
var midnight = TimeZoneInfo.ConvertTimeToUtc(AppInfo.LocalNow.Date, AppInfo.TimeZone);
return (int)await _db.ScalarAsync<long>(
"SELECT count(*) FROM promo_redemptions WHERE ts >= $1 AND outcome = ANY($2)", midnight,
new[] { OutcomeCode(RedeemOutcome.Credited), OutcomeCode(RedeemOutcome.CreditedWithWarning) }).ConfigureAwait(false);
}
private static readonly string[] FinalCodes = Enum.GetValues<RedeemOutcome>()
.Where(o => new RedeemResult(o, null, null, null, "").Final).Select(OutcomeCode).ToArray();
/// <summary>Il codice dell'esito in <c>promo_redemptions.outcome</c>.</summary>
public static string OutcomeCode(RedeemOutcome o) => o switch
{
RedeemOutcome.Credited => "credited",
RedeemOutcome.CreditedWithWarning => "credited-warning",
RedeemOutcome.AlreadyUsed => "already-used",
RedeemOutcome.Expired => "expired",
RedeemOutcome.NotExists => "not-exists",
RedeemOutcome.VerifyRequired => "verify",
RedeemOutcome.NoSession => "no-session",
RedeemOutcome.Refused => "refused",
RedeemOutcome.BadRequest => "bad-request",
RedeemOutcome.NetworkError => "network",
_ => "unknown"
};
private string Done(string text)
{
_lastSummary = text;
Note(text);
return text;
}
private void Note(string text, bool warn = false)
{
var clean = LogText.Clean(text);
var now = DateTime.UtcNow;
lock (_sync)
{
_lines.AddFirst(new LogLine(now, clean));
while (_lines.Count > 500) _lines.RemoveLast();
}
_file?.Write(LogKind, AppInfo.ToLocal(now), clean);
if (warn) _log.Warn(Tag, clean); else _log.Info(Tag, clean);
Bump();
}
private void Bump() => Version++;
private static State LoadState(IDocumentStore docs)
{
try { return JsonSerializer.Deserialize<State>(docs.Get(StateKey) ?? "{}") ?? new State(); }
catch (JsonException) { return new State(); }
}
private void SaveState() => _documents.Set(StateKey, JsonSerializer.Serialize(_state));
private static async Task<bool> DelayAsync(TimeSpan wait, CancellationToken ct)
{
try { await Task.Delay(wait, ct).ConfigureAwait(false); return true; }
catch (OperationCanceledException) { return false; }
}
public void Dispose()
{
_external.Dispose();
_gate.Dispose();
}
}
+79
View File
@@ -0,0 +1,79 @@
using System.Globalization;
using System.Net;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Mimante.Bidoo.FreeBids;
/// <summary>Un collegamento promozionale come lo pubblica la fonte (puntateaste.it).</summary>
/// <param name="SourceId">L'id della riga alla fonte (cresce con le aggiunte).</param>
/// <param name="Link">Il collegamento così com'è, già senza marcatori HTML e con le entità decodificate.</param>
/// <param name="Points">Le puntate dichiarate dalla fonte (indicative: conta il saldo).</param>
/// <param name="Fast">Collegamento a tempo: la fonte lo mostra solo per un'ora.</param>
/// <param name="AddedUnix">Quando la fonte l'ha aggiunto (secondi Unix).</param>
public sealed record PromoFeedItem(long SourceId, string Link, int Points, bool Fast, long AddedUnix);
/// <summary>
/// La risposta della fonte dei collegamenti: un array JSON, il più nuovo prima, con <c>id</c>, <c>link</c>,
/// <c>short_link</c>, <c>punti</c>, <c>fast</c>, <c>approved</c>, <c>time</c>. Tollerante: una riga strana si
/// salta, un campo mancante prende un valore neutro. Pura.
/// </summary>
public static partial class PromoFeed
{
public sealed record Result(IReadOnlyList<PromoFeedItem> Items, int Skipped, string? Error);
public static Result Parse(string? body)
{
if (string.IsNullOrWhiteSpace(body)) return new Result([], 0, "risposta vuota");
JsonDocument doc;
try { doc = JsonDocument.Parse(body, new JsonDocumentOptions { AllowTrailingCommas = true }); }
catch (JsonException) { return new Result([], 0, "la fonte non ha risposto in JSON: il formato è cambiato?"); }
using (doc)
{
if (doc.RootElement.ValueKind != JsonValueKind.Array) return new Result([], 0, "la fonte non ha risposto con un elenco");
var items = new List<PromoFeedItem>();
var skipped = 0;
foreach (var row in doc.RootElement.EnumerateArray())
{
if (row.ValueKind != JsonValueKind.Object) { skipped++; continue; }
if (Int(row, "approved") is 0) { skipped++; continue; }
// La pagina della fonte usa short_link quando c'è; un collegamento accorciato però non si segue mai
// (il controllo lo scarta), quindi qui vale link e short_link solo in sua mancanza.
var link = Clean(Str(row, "link"));
if (string.IsNullOrEmpty(link)) link = Clean(Str(row, "short_link"));
if (string.IsNullOrEmpty(link)) { skipped++; continue; }
items.Add(new PromoFeedItem(Int(row, "id") ?? 0, link, (int)(Int(row, "punti") ?? 0), Int(row, "fast") is 1, Int(row, "time") ?? 0));
}
return new Result(items, skipped, null);
}
}
/// <summary>Il corpo della richiesta alla fonte: <c>l</c> è la mezzanotte di Roma del giorno, in secondi Unix.</summary>
public static string Body(string template, DateOnly dayRome, TimeZoneInfo rome)
{
var midnight = TimeZoneInfo.ConvertTimeToUtc(dayRome.ToDateTime(TimeOnly.MinValue), rome);
var unix = new DateTimeOffset(midnight, TimeSpan.Zero).ToUnixTimeSeconds();
return template.Replace("{midnight}", unix.ToString(CultureInfo.InvariantCulture), StringComparison.Ordinal);
}
/// <summary>Toglie i marcatori HTML (i collegamenti sono scritti dagli utenti) e decodifica le entità.</summary>
internal static string Clean(string? s) => string.IsNullOrWhiteSpace(s) ? "" : WebUtility.HtmlDecode(Tags().Replace(s, "")).Trim();
private static string? Str(JsonElement o, string name) =>
o.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;
private static long? Int(JsonElement o, string name)
{
if (!o.TryGetProperty(name, out var v)) return null;
return v.ValueKind switch
{
JsonValueKind.Number when v.TryGetInt64(out var n) => n,
JsonValueKind.String when long.TryParse(v.GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) => n,
_ => null
};
}
[GeneratedRegex("<[^>]*>")]
private static partial Regex Tags();
}
+66
View File
@@ -0,0 +1,66 @@
using System.Text.RegularExpressions;
namespace Mimante.Bidoo.FreeBids;
/// <summary>Un collegamento promozionale di Bidoo controllato: il codice, la firma e l'indirizzo da aprire così com'è.</summary>
public sealed record PromoLink(string Code, string Sign, Uri Url);
/// <summary>
/// Il controllo di un collegamento prima di aprirlo con la sessione di Bidoo. Passa solo un indirizzo
/// <c>https</c> sull'host esatto di Bidoo (dai riferimenti), su uno dei percorsi ammessi, senza utente né porta,
/// con <c>promocode</c> e <c>sign</c> validi e nessun altro parametro che non sia ammesso. Tutto il resto
/// (accorciatori, altri siti, host simili, redirezioni) si scarta con il motivo: non si segue mai. Pura.
/// </summary>
public static partial class PromoLinkCheck
{
public sealed record Verdict(PromoLink? Link, string? Reason)
{
public bool Ok => Link != null;
}
public static Verdict Check(string? text, string host, IReadOnlyCollection<string> paths, IReadOnlyCollection<string>? extraParameters = null)
{
var raw = PromoFeed.Clean(text);
if (raw.Length == 0) return No("collegamento vuoto");
if (raw.Length > 600) return No("collegamento troppo lungo");
if (!Uri.TryCreate(raw, UriKind.Absolute, out var url)) return No("non è un indirizzo");
if (url.Scheme != Uri.UriSchemeHttps) return No("non è https");
if (!string.Equals(url.Host, host, StringComparison.OrdinalIgnoreCase)) return No($"non è di {host} ({url.Host})");
if (!url.IsDefaultPort) return No("porta non ammessa");
if (url.UserInfo.Length > 0) return No("indirizzo con utente");
if (!paths.Contains(url.AbsolutePath, StringComparer.OrdinalIgnoreCase)) return No($"percorso non ammesso ({url.AbsolutePath})");
if (url.Fragment.Length > 1) return No("indirizzo con frammento");
string? code = null, sign = null;
foreach (var part in url.Query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries))
{
var eq = part.IndexOf('=');
var name = Uri.UnescapeDataString(eq < 0 ? part : part[..eq]);
var value = eq < 0 ? "" : Uri.UnescapeDataString(part[(eq + 1)..].Replace('+', ' '));
switch (name)
{
case "promocode" when code == null: code = value.Trim(); break;
case "sign" when sign == null: sign = value.Trim(); break;
case "promocode" or "sign": return No($"parametro {name} ripetuto");
default:
if (extraParameters == null || !extraParameters.Contains(name)) return No($"parametro non ammesso ({name})");
break;
}
}
if (string.IsNullOrEmpty(code)) return No("manca promocode");
if (!Code().IsMatch(code)) return No("promocode con caratteri non ammessi");
if (string.IsNullOrEmpty(sign)) return No("manca sign");
if (!Sign().IsMatch(sign)) return No("sign non valida");
// La firma resta com'è: si manda a Bidoo invariata.
return new Verdict(new PromoLink(code, sign, url), null);
}
private static Verdict No(string reason) => new(null, reason);
[GeneratedRegex("^[A-Za-z0-9_.-]{1,100}$")]
private static partial Regex Code();
[GeneratedRegex("^[0-9a-fA-F]{16,128}$")]
private static partial Regex Sign();
}
+132
View File
@@ -0,0 +1,132 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
namespace Mimante.Bidoo.FreeBids;
/// <summary>Come è andato un riscatto, dalla risposta del secondo passo.</summary>
public enum RedeemOutcome
{
/// <summary><c>ok-&lt;saldo&gt;</c>: puntate accreditate.</summary>
Credited,
/// <summary><c>warningOrigin-&lt;saldo&gt;-&lt;avviso&gt;</c>: accreditate, con un avviso di Bidoo sulla provenienza. Ferma il riscatto automatico.</summary>
CreditedWithWarning,
/// <summary><c>clicked</c>: il codice era già stato usato da questo conto.</summary>
AlreadyUsed,
/// <summary><c>expired-&lt;unix&gt;</c>: codice scaduto.</summary>
Expired,
/// <summary><c>no</c>: Bidoo non conosce il codice.</summary>
NotExists,
/// <summary><c>showVerify</c>: Bidoo chiede una verifica a mano. Ferma il riscatto automatico.</summary>
VerifyRequired,
/// <summary>401: senza sessione.</summary>
NoSession,
/// <summary>403: codice o firma rifiutati.</summary>
Refused,
/// <summary>400: la pagina del codice non era stata aperta prima (o il passo è stato ripetuto).</summary>
BadRequest,
/// <summary>Qualcos'altro: si registra la risposta e si ferma il riscatto automatico.</summary>
Unknown,
/// <summary>Errore di rete o tempo scaduto: nessuna risposta.</summary>
NetworkError
}
/// <summary>L'esito letto da una risposta, con il saldo e la scadenza quando Bidoo li dà.</summary>
public sealed record RedeemResult(RedeemOutcome Outcome, int? Balance, DateTime? ExpiredUtc, string? Warning, string Raw)
{
/// <summary>Il codice è consumato o inutilizzabile: non si riprova.</summary>
public bool Final => Outcome is RedeemOutcome.Credited or RedeemOutcome.CreditedWithWarning or RedeemOutcome.AlreadyUsed
or RedeemOutcome.Expired or RedeemOutcome.NotExists or RedeemOutcome.Refused;
/// <summary>Un esito che chiede di fermare il riscatto automatico finché l'utente non guarda.</summary>
public bool Pause => Outcome is RedeemOutcome.CreditedWithWarning or RedeemOutcome.VerifyRequired or RedeemOutcome.Unknown
or RedeemOutcome.NoSession;
public string Describe() => Outcome switch
{
RedeemOutcome.Credited => Balance is { } b ? $"accreditate, saldo {b}" : "accreditate",
RedeemOutcome.CreditedWithWarning => $"accreditate con un avviso di Bidoo{(Warning is { Length: > 0 } w ? ": " + w : "")}",
RedeemOutcome.AlreadyUsed => "codice già usato",
RedeemOutcome.Expired => ExpiredUtc is { } e ? $"scaduto il {e.ToLocalTime():dd/MM/yyyy HH:mm}" : "scaduto",
RedeemOutcome.NotExists => "codice sconosciuto a Bidoo",
RedeemOutcome.VerifyRequired => "Bidoo chiede una verifica",
RedeemOutcome.NoSession => "sessione di Bidoo assente",
RedeemOutcome.Refused => "codice o firma rifiutati",
RedeemOutcome.BadRequest => "richiesta rifiutata: la pagina del codice non era aperta",
RedeemOutcome.NetworkError => "nessuna risposta",
_ => "risposta non riconosciuta"
};
}
/// <summary>Le parole con cui Bidoo risponde al secondo passo (dai riferimenti, correggibili senza rilascio).</summary>
public sealed class RedeemGrammar
{
public string CreditedPrefix { get; set; } = "ok-";
public string WarningPrefix { get; set; } = "warningOrigin-";
public string ExpiredPrefix { get; set; } = "expired-";
public string AlreadyUsed { get; set; } = "clicked";
public string NotExists { get; set; } = "no";
public string Verify { get; set; } = "showVerify";
}
/// <summary>Legge la risposta del secondo passo (<c>push_promotions.php</c>). Pura.</summary>
public static class PromoResponse
{
public static RedeemResult Parse(int? status, string? body, RedeemGrammar g)
{
var raw = (body ?? "").Trim();
if (status is null or 0) return new RedeemResult(RedeemOutcome.NetworkError, null, null, null, raw);
if (status == 401) return new RedeemResult(RedeemOutcome.NoSession, null, null, null, raw);
if (status == 403) return new RedeemResult(RedeemOutcome.Refused, null, null, null, raw);
if (status == 400) return new RedeemResult(RedeemOutcome.BadRequest, null, null, null, raw);
if (status is < 200 or >= 300) return new RedeemResult(RedeemOutcome.Unknown, null, null, null, raw);
if (Starts(raw, g.CreditedPrefix))
return new RedeemResult(RedeemOutcome.Credited, Number(raw[g.CreditedPrefix.Length..]), null, null, raw);
if (Starts(raw, g.WarningPrefix))
{
// warningOrigin-<saldo>-<base64 di {"title":…,"subtitle":…}>
var rest = raw[g.WarningPrefix.Length..];
var dash = rest.IndexOf('-');
var balance = Number(dash < 0 ? rest : rest[..dash]);
return new RedeemResult(RedeemOutcome.CreditedWithWarning, balance, null, dash < 0 ? null : Warning(rest[(dash + 1)..]), raw);
}
if (Starts(raw, g.ExpiredPrefix))
{
var unix = Number(raw[g.ExpiredPrefix.Length..]);
return new RedeemResult(RedeemOutcome.Expired, null, unix is { } u ? DateTimeOffset.FromUnixTimeSeconds(u).UtcDateTime : null, null, raw);
}
if (raw == g.AlreadyUsed) return new RedeemResult(RedeemOutcome.AlreadyUsed, null, null, null, raw);
if (raw == g.NotExists) return new RedeemResult(RedeemOutcome.NotExists, null, null, null, raw);
if (raw == g.Verify) return new RedeemResult(RedeemOutcome.VerifyRequired, null, null, null, raw);
return new RedeemResult(RedeemOutcome.Unknown, null, null, null, raw);
}
private static bool Starts(string s, string prefix) => prefix.Length > 0 && s.StartsWith(prefix, StringComparison.Ordinal);
private static int? Number(string s)
{
var t = s.Trim().Replace(".", "", StringComparison.Ordinal);
return int.TryParse(t, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : null;
}
/// <summary>Il titolo e il sottotitolo dell'avviso, senza marcatori; null se non si legge.</summary>
private static string? Warning(string base64)
{
try
{
var json = Encoding.UTF8.GetString(Convert.FromBase64String(base64.Trim()));
using var doc = JsonDocument.Parse(json);
string? Field(string n) => doc.RootElement.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.String ? PromoFeed.Clean(v.GetString()) : null;
var text = string.Join(" - ", new[] { Field("title"), Field("subtitle") }.Where(x => !string.IsNullOrEmpty(x)));
return text.Length == 0 ? null : text.Length > 300 ? text[..300] : text;
}
catch (Exception e) when (e is FormatException or JsonException or ArgumentException)
{
return null;
}
}
}
@@ -0,0 +1,45 @@
namespace Mimante.Bidoo.FreeBids;
/// <summary>Che cosa si sa di un codice già visto.</summary>
/// <param name="Attempts">Tentativi fatti (ognuno è la coppia dei due passi).</param>
/// <param name="Final">Consumato o inutilizzabile: non si riprova mai.</param>
public sealed record KnownCode(int Attempts, bool Final);
/// <summary>Un candidato del giro: il collegamento controllato e da dove viene.</summary>
public sealed record RedeemCandidate(PromoLink Link, string Source, int Points, bool Fast, long AddedUnix);
/// <summary>I tetti del giro (dalle impostazioni).</summary>
public sealed record RedeemLimits(int MaxPerRun, int MaxPerDay, int MaxAttempts);
/// <summary>
/// Quali collegamenti aprire in questo giro. Prudenza prima di tutto: niente se il riscatto è in pausa; uno solo
/// finché il primo accredito non è confermato dal saldo; mai un codice già consumato o oltre i tentativi; i tetti
/// del giro e del giorno. Prima i collegamenti a tempo (la fonte li tiene un'ora), poi i più nuovi. Pura.
/// </summary>
public static class RedeemPlanner
{
public sealed record Plan(IReadOnlyList<RedeemCandidate> Open, string Why);
public static Plan Choose(IEnumerable<RedeemCandidate> candidates, IReadOnlyDictionary<string, KnownCode> known,
RedeemLimits limits, int redeemedToday, bool confirmed, bool paused)
{
if (paused) return new Plan([], "riscatto in pausa");
var leftToday = limits.MaxPerDay > 0 ? limits.MaxPerDay - redeemedToday : int.MaxValue;
if (leftToday <= 0) return new Plan([], $"tetto del giorno raggiunto ({limits.MaxPerDay})");
var fresh = candidates
.GroupBy(c => c.Link.Code, StringComparer.Ordinal).Select(g => g.First())
.Where(c => !known.TryGetValue(c.Link.Code, out var k) || (!k.Final && k.Attempts < Math.Max(1, limits.MaxAttempts)))
.OrderByDescending(c => c.Fast).ThenByDescending(c => c.AddedUnix).ThenBy(c => c.Link.Code, StringComparer.Ordinal)
.ToList();
if (fresh.Count == 0) return new Plan([], "nessun collegamento nuovo");
var cap = Math.Min(leftToday, limits.MaxPerRun > 0 ? limits.MaxPerRun : int.MaxValue);
if (!confirmed) cap = 1;
var open = fresh.Take(cap).ToList();
var why = !confirmed
? "uno solo finché il primo accredito non è confermato dal saldo"
: open.Count < fresh.Count ? $"{open.Count} di {fresh.Count}: tetto del giro o del giorno" : $"{open.Count} nuovi";
return new Plan(open, why);
}
}
+25
View File
@@ -125,5 +125,30 @@
"statusOn": "ON",
"statusOff": "OFF",
"statusStop": "STOP"
},
// Riscatto delle puntate gratuite (ADR 0015). La fonte si legge senza il cookie di Bidoo; un collegamento
// si apre solo se è https sull'host di baseUrl, su uno dei percorsi ammessi, con promocode e sign.
"freeBids": {
"feedUrl": "https://puntateaste.it/index.php",
// {midnight}: la mezzanotte di Roma del giorno, in secondi Unix. Si chiedono oggi e ieri.
"feedBody": "s=1&l={midnight}",
"feedReferer": "https://puntateaste.it/",
"promoPaths": [ "/", "/index.php" ],
"promoExtraParameters": [ "kp", "by" ],
// Il secondo passo, dopo aver aperto la pagina del codice con la sessione: una sola volta.
"redeem": "/push_promotions.php?code={code}&sign={sign}&kp=&by=",
"grammar": {
"creditedPrefix": "ok-",
"warningPrefix": "warningOrigin-",
"expiredPrefix": "expired-",
"alreadyUsed": "clicked",
"notExists": "no",
"verify": "showVerify"
},
// 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"
}
}
@@ -67,6 +67,9 @@ public sealed record ArchiveTable(
new("watched_products", ArchiveSplit.Whole, null, "product_key", "I prodotti seguiti."),
new("product_stats", ArchiveSplit.Whole, null, "product_key", "Le statistiche calcolate per prodotto."),
new("risk_ledger", ArchiveSplit.Whole, null, "id", "Il registro del rischio: spese e vincite che contano per i tetti."),
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("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'" }),
+1 -1
View File
@@ -37,7 +37,7 @@ public sealed class Maintenance
public static readonly string[] BackupTables =
{
"schema_migrations", "settings", "documents", "items", "auctions", "my_bids", "auction_forecasts", "bidders",
"risk_ledger", "products", "watched_products", "product_stats"
"risk_ledger", "products", "watched_products", "product_stats", "promo_redemptions", "chests"
};
public long? LastSizeBytes { get; private set; }
@@ -0,0 +1,37 @@
-- Riscatto delle puntate gratuite e forzieri (ADR 0015). Solo tabelle nuove.
-- Serve allo storico per: ogni riscatto tentato, con la fonte, l'esito di Bidoo, il saldo prima e dopo e le
-- puntate guadagnate davvero (dal saldo, non da quelle dichiarate). La pagina «Puntate gratis» e i tetti del
-- giorno leggono da qui.
CREATE TABLE IF NOT EXISTS promo_redemptions (
id bigserial PRIMARY KEY,
ts timestamptz NOT NULL DEFAULT now(),
code text NOT NULL,
source text NOT NULL,
source_id bigint,
link text NOT NULL,
points_declared int,
outcome text NOT NULL,
balance_before int,
balance_after int,
gained int,
page_status int,
response text,
note text,
latency_ms int,
manual boolean NOT NULL DEFAULT false
);
CREATE INDEX IF NOT EXISTS promo_redemptions_code ON promo_redemptions(code);
CREATE INDEX IF NOT EXISTS promo_redemptions_ts ON promo_redemptions(ts);
-- Serve allo storico per: i forzieri visti nelle categorie (solo avviso, il bot non li apre), una riga per
-- forziere e giorno, con quando è stato visto la prima e l'ultima volta.
CREATE TABLE IF NOT EXISTS chests (
id bigserial PRIMARY KEY,
first_seen timestamptz NOT NULL DEFAULT now(),
last_seen timestamptz NOT NULL DEFAULT now(),
tag int NOT NULL,
url text NOT NULL,
day date NOT NULL,
UNIQUE (tag, url, day)
);
+14
View File
@@ -1,4 +1,5 @@
using Mimante.Bidoo;
using Mimante.Bidoo.FreeBids;
using Mimante.Data;
using Mimante.Engine;
using Mimante.Ml;
@@ -43,6 +44,9 @@ public sealed class BotWorld : IAsyncDisposable
public required ProductLimits Limits { get; init; }
public SessionChecker? Checker { get; private init; }
/// <summary>Riscatto delle puntate gratuite e forzieri: solo nel mondo vero, mai nel simulatore.</summary>
public FreeBidsService? FreeBids { get; private init; }
/// <summary>C'è un utente Bidoo collegato (o è il simulatore)? Senza, si segue e si impara ma non si punta.</summary>
public bool HasSession { get; private init; }
@@ -161,6 +165,10 @@ public sealed class BotWorld : IAsyncDisposable
Watcher = new ProductWatcher(catalog, bot.Products, monitor, () => settings.Current, bot.Log),
Limits = limits,
Checker = sim == null && hasSession ? new SessionChecker(api, account, bot.Log) : null,
FreeBids = sim == null
? new FreeBidsService(api, refs, () => settings.Current, account, bot.Documents, bot.Queue, bot.Db, bot.Log, bot.Host.FileLog,
bot.Telegram, () => hasSession && account.Status == SessionStatus.Valid)
: null,
HasSession = hasSession
};
@@ -190,6 +198,11 @@ public sealed class BotWorld : IAsyncDisposable
if (Checker != null) _jobs.Add(Checker.RunAsync(ct));
_jobs.Add(Watcher.RunAsync(ct));
if (!IsSimulator) _jobs.Add(BackfillLoopAsync(bot, ct));
if (FreeBids != null)
{
_jobs.Add(FreeBids.RunAsync(ct));
_jobs.Add(FreeBids.RunChestsAsync(ct));
}
bot.Log.Info("AVVIO", IsSimulator
? "Modalità debug: stai vedendo il simulatore (nessuna sessione Bidoo salvata)"
: HasSession
@@ -257,6 +270,7 @@ public sealed class BotWorld : IAsyncDisposable
Learning.Save(force: true);
Latency.Save(force: true);
Lane.Dispose();
FreeBids?.Dispose();
Transport.Dispose();
if (Sim != null) await Sim.DisposeAsync().ConfigureAwait(false);
_cts.Dispose();
+14 -2
View File
@@ -26,6 +26,7 @@ public sealed class BidooTransport : IDisposable
private readonly Func<BidooReferences> _refs;
private readonly HttpMessageHandler _handler;
private readonly HttpClient _client;
private readonly Lazy<HttpClient> _noRedirect;
private readonly SemaphoreSlim _concurrency;
private readonly TokenBucket _limiter;
@@ -54,6 +55,16 @@ public sealed class BidooTransport : IDisposable
};
_client.DefaultRequestHeaders.ConnectionClose = false;
// Per i collegamenti promozionali: nessuna redirezione seguita (il cookie scritto a mano la seguirebbe
// ovunque). Con un handler dato dai test si usa quello.
_noRedirect = new Lazy<HttpClient>(() =>
{
if (handler != null) return _client;
var h = CreateHandler(4);
h.AllowAutoRedirect = false;
return new HttpClient(h, disposeHandler: true) { Timeout = _client.Timeout };
});
_concurrency = new SemaphoreSlim(Math.Max(1, limits.MaxConcurrency), Math.Max(1, limits.MaxConcurrency));
_limiter = new TokenBucket(requestsPerSecond);
}
@@ -180,7 +191,7 @@ public sealed class BidooTransport : IDisposable
}
/// <summary>Invia rispettando ritmo, freno e concorrenza (salvo le Critical).</summary>
public async Task<HttpOutcome> SendAsync(HttpRequestMessage request, RequestPriority priority, CancellationToken ct)
public async Task<HttpOutcome> SendAsync(HttpRequestMessage request, RequestPriority priority, CancellationToken ct, bool followRedirects = true)
{
var critical = priority == RequestPriority.Critical;
@@ -194,7 +205,7 @@ public sealed class BidooTransport : IDisposable
try
{
var outcome = await ExecuteAsync(_client, request, ct).ConfigureAwait(false);
var outcome = await ExecuteAsync(followRedirects ? _client : _noRedirect.Value, request, ct).ConfigureAwait(false);
Interlocked.Increment(ref _sent);
if (!outcome.Success) Interlocked.Increment(ref _failed);
@@ -277,6 +288,7 @@ public sealed class BidooTransport : IDisposable
public void Dispose()
{
if (_noRedirect.IsValueCreated && !ReferenceEquals(_noRedirect.Value, _client)) _noRedirect.Value.Dispose();
_client.Dispose();
_concurrency.Dispose();
}
+73
View File
@@ -0,0 +1,73 @@
using System.Diagnostics;
using System.Net;
using System.Text;
namespace Mimante.Net;
/// <summary>
/// Le richieste verso siti diversi da Bidoo (la fonte dei collegamenti promozionali). Senza cookie per
/// costruzione: un client a parte, senza contenitore di cookie, che non conosce la sessione di Bidoo e non segue
/// redirezioni. Classe a parte e non un parametro del trasporto, perché la scelta si veda nel codice che la usa.
/// </summary>
public sealed class ExternalHttp : IDisposable
{
private readonly HttpClient _client;
public ExternalHttp(HttpMessageHandler? handler = null, TimeSpan? timeout = null)
{
_client = new HttpClient(handler ?? new SocketsHttpHandler
{
UseCookies = false,
UseProxy = false,
AllowAutoRedirect = false,
AutomaticDecompression = DecompressionMethods.All,
ConnectTimeout = TimeSpan.FromSeconds(10),
PooledConnectionLifetime = TimeSpan.FromMinutes(10)
}, disposeHandler: handler == null)
{
Timeout = timeout ?? TimeSpan.FromSeconds(20)
};
}
/// <summary>Una POST di un modulo, come la manda la pagina della fonte (AJAX).</summary>
public async Task<HttpOutcome> PostFormAsync(string url, string body, string? referer, string userAgent, CancellationToken ct)
{
using var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded")
};
var h = request.Headers;
h.TryAddWithoutValidation("User-Agent", userAgent);
h.TryAddWithoutValidation("Accept", "application/json, text/javascript, */*; q=0.01");
h.TryAddWithoutValidation("Accept-Language", "it-IT,it;q=0.9");
h.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
if (!string.IsNullOrEmpty(referer)) h.TryAddWithoutValidation("Referer", referer);
var start = Stopwatch.GetTimestamp();
try
{
using var response = await _client.SendAsync(request, ct).ConfigureAwait(false);
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var received = Stopwatch.GetTimestamp();
return new HttpOutcome
{
Success = response.IsSuccessStatusCode,
StatusCode = (int)response.StatusCode,
Body = text,
LatencyMs = (int)((received - start) * 1000 / Stopwatch.Frequency),
SentTicks = start,
ReceivedTicks = received
};
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
return HttpOutcome.Failure(ex is TaskCanceledException ? "nessuna risposta nel tempo massimo" : ex.Message, start);
}
}
public void Dispose() => _client.Dispose();
}
+34
View File
@@ -183,6 +183,37 @@ public sealed class AppSettings
public int AutoAddMaxStartMinutes { get; set; } = 60;
public bool AutoAddOnlyNotStarted { get; set; }
// ── Puntate gratis (Bidoo/FreeBids, ADR 0015) ───────────────────────
/// <summary>Riscatto automatico dei collegamenti promozionali. Spento di fabbrica; si accende dalla pagina «Puntate gratis».</summary>
public bool FreeBidsEnabled { get; set; }
/// <summary>Minuti fra un giro e l'altro (più una pausa casuale fino a 2 minuti).</summary>
public int FreeBidsIntervalMinutes { get; set; } = 30;
/// <summary>Collegamenti al massimo per giro; 0 = nessun limite.</summary>
public int FreeBidsMaxPerRun { get; set; } = 5;
/// <summary>Riscatti al massimo per giorno; 0 = nessun limite.</summary>
public int FreeBidsMaxPerDay { get; set; } = 30;
/// <summary>Tentativi per un codice che non ha dato un esito definitivo (rete, richiesta rifiutata).</summary>
public int FreeBidsMaxAttempts { get; set; } = 3;
/// <summary>Pausa casuale fra un riscatto e il successivo, in secondi.</summary>
public int FreeBidsPauseMinSeconds { get; set; } = 5;
public int FreeBidsPauseMaxSeconds { get; set; } = 20;
/// <summary>Ore in cui si riscatta (ora di Roma), da inizio compreso a fine esclusa; uguali = sempre.</summary>
public int FreeBidsHoursStart { get; set; } = 8;
public int FreeBidsHoursEnd { get; set; } = 24;
/// <summary>Giro delle categorie per i forzieri: solo avviso, il bot non li apre.</summary>
public bool ChestWatchEnabled { get; set; }
/// <summary>Minuti fra un giro dei forzieri e l'altro.</summary>
public int ChestWatchMinutes { get; set; } = 20;
// ── Limiti consigliati per prodotto (solo consiglio, mai applicati da soli) ─
/// <summary>Quota di chiusure passate che il prezzo massimo consigliato copre.</summary>
@@ -203,6 +234,9 @@ public sealed class AppSettings
public bool TelegramNotifySession { get; set; } = true;
public bool TelegramNotifyRisk { get; set; } = true;
/// <summary>Un messaggio per ogni riscatto riuscito, per una pausa del riscatto e per un forziere trovato.</summary>
public bool TelegramNotifyFreeBids { get; set; } = true;
/// <summary>Riepilogo periodico in minuti; 0 = mai.</summary>
public int TelegramSummaryMinutes { get; set; } = 60;
+10
View File
@@ -207,6 +207,16 @@ public sealed class SettingsStore
s.AutoAddMaxAuctions = Math.Max(0, s.AutoAddMaxAuctions);
s.AutoAddMaxStartMinutes = Math.Max(0, s.AutoAddMaxStartMinutes);
s.FreeBidsIntervalMinutes = Math.Clamp(s.FreeBidsIntervalMinutes, 10, 24 * 60);
s.FreeBidsMaxPerRun = Math.Clamp(s.FreeBidsMaxPerRun, 0, 100);
s.FreeBidsMaxPerDay = Math.Clamp(s.FreeBidsMaxPerDay, 0, 1000);
s.FreeBidsMaxAttempts = Math.Clamp(s.FreeBidsMaxAttempts, 1, 10);
s.FreeBidsPauseMinSeconds = Math.Clamp(s.FreeBidsPauseMinSeconds, 2, 600);
s.FreeBidsPauseMaxSeconds = Math.Clamp(s.FreeBidsPauseMaxSeconds, s.FreeBidsPauseMinSeconds, 600);
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.SuggestedCoveragePercent = Math.Clamp(s.SuggestedCoveragePercent, 50, 99);
s.SuggestedValueTolerancePercent = Math.Clamp(s.SuggestedValueTolerancePercent, 0, 100);
s.SuggestedMinPercentile = Math.Clamp(s.SuggestedMinPercentile, 0, 50);
+48
View File
@@ -41,6 +41,7 @@ public static class Api
"/api/prodotti" => await ProductsAsync(bot).ConfigureAwait(false),
"/api/storico" => await HistoryAsync(bot, q).ConfigureAwait(false),
"/api/apprendimento" => await LearningAsync(bot).ConfigureAwait(false),
"/api/puntate-gratis" => await FreeBidsAsync(bot).ConfigureAwait(false),
"/api/registro" => LogPage(bot, q),
"/api/esportazioni" => ExportList(bot),
"/api/immagine" => null,
@@ -320,6 +321,53 @@ public static class Api
// ── Apprendimento ────────────────────────────────────────────────────
/// <summary>La pagina «Puntate gratis»: contatori, riscatti, forzieri e registro completo (in memoria).</summary>
private static async Task<object> FreeBidsAsync(Bot bot)
{
var service = bot.World?.FreeBids;
var midnight = TimeZoneInfo.ConvertTimeToUtc(AppInfo.LocalNow.Date, AppInfo.TimeZone);
var counts = await bot.Db.QueryOneAsync(
"SELECT count(*) FILTER (WHERE ts >= $1 AND outcome IN ('credited', 'credited-warning')) AS n_today, " +
" coalesce(sum(gained) FILTER (WHERE ts >= $1 AND gained > 0), 0) AS g_today, " +
" count(*) FILTER (WHERE ts >= $1 - interval '6 days' AND outcome IN ('credited', 'credited-warning')) AS n_week, " +
" coalesce(sum(gained) FILTER (WHERE ts >= $1 - interval '6 days' AND gained > 0), 0) AS g_week, " +
" count(*) FILTER (WHERE outcome IN ('credited', 'credited-warning')) AS n_all, " +
" coalesce(sum(gained) FILTER (WHERE gained > 0), 0) AS g_all, count(*) AS attempts FROM promo_redemptions",
r => new Dictionary<string, object?>
{
["today"] = r.Long("n_today"), ["todayBids"] = r.Long("g_today"),
["week"] = r.Long("n_week"), ["weekBids"] = r.Long("g_week"),
["all"] = r.Long("n_all"), ["allBids"] = r.Long("g_all"), ["attempts"] = r.Long("attempts")
}, midnight).ConfigureAwait(false);
var redemptions = await bot.Db.QueryAsync(
"SELECT ts, code, source, outcome, points_declared, balance_before, balance_after, gained, note, manual, response " +
"FROM promo_redemptions ORDER BY ts DESC LIMIT 300",
r => new Dictionary<string, object?>
{
["at"] = r.Date("ts"), ["code"] = r.Str("code"), ["source"] = r.Str("source"), ["outcome"] = r.Str("outcome"),
["declared"] = r.IntOrNull("points_declared"), ["before"] = r.IntOrNull("balance_before"),
["after"] = r.IntOrNull("balance_after"), ["gained"] = r.IntOrNull("gained"), ["note"] = r.StrOrNull("note"),
["manual"] = r.BoolOrNull("manual") ?? false, ["response"] = r.StrOrNull("response")
}).ConfigureAwait(false);
var chests = await bot.Db.QueryAsync(
"SELECT first_seen, last_seen, tag, url FROM chests ORDER BY first_seen DESC LIMIT 200",
r => new Dictionary<string, object?>
{
["first"] = r.Date("first_seen"), ["last"] = r.Date("last_seen"), ["tag"] = r.Int("tag"), ["url"] = r.Str("url")
}).ConfigureAwait(false);
return new Dictionary<string, object?>
{
["present"] = service != null,
["counts"] = counts,
["redemptions"] = redemptions,
["chests"] = chests,
["log"] = service?.Lines(500).Select(l => new Dictionary<string, object?> { ["at"] = l.AtUtc, ["text"] = l.Text }).ToList()
};
}
private static async Task<object> LearningAsync(Bot bot)
{
var w = bot.World;
+29
View File
@@ -171,6 +171,35 @@ public static class Views
["endedAt"] = s.EndedUtc
};
/// <summary>
/// Il riscatto delle puntate gratuite: stato, pausa, giri e le ultime righe del registro. Nel simulatore
/// <c>world</c> è assente: la pagina dice che il riscatto vive solo sul sito vero.
/// </summary>
public static Dictionary<string, object?> FreeBids(Bidoo.FreeBids.FreeBidsService? service)
{
if (service == null) return new() { ["t"] = "freebids", ["present"] = false };
var s = service.Current();
return new()
{
["t"] = "freebids",
["present"] = true,
["enabled"] = s.Enabled,
["available"] = s.Available,
["unavailable"] = s.Unavailable,
["running"] = s.Running,
["paused"] = s.Paused,
["pauseReason"] = s.PauseReason,
["confirmed"] = s.Confirmed,
["lastRunAt"] = s.LastRunUtc,
["nextRunAt"] = s.NextRunUtc,
["lastSummary"] = s.LastSummary,
["chestWatch"] = s.ChestWatch,
["lastChestAt"] = s.LastChestUtc,
["chestsToday"] = s.ChestsToday,
["log"] = service.Lines(60).Select(l => new Dictionary<string, object?> { ["at"] = l.AtUtc, ["text"] = l.Text }).ToList()
};
}
/// <summary>Il pannello dettagli dell'asta selezionata.</summary>
public static Dictionary<string, object?> AuctionDetail(AuctionInfo a, BotWorld world, AppSettings settings)
{
+22
View File
@@ -399,6 +399,28 @@ public sealed partial class WebSocketHub
? new Ack(true, "Annullamento chiesto: l'esportazione si ferma senza lasciare file a metà")
: new Ack(false, "Nessuna esportazione in corso");
// ── puntate gratis ────────────────────────────────────────
// L'interruttore è l'impostazione FreeBidsEnabled (settings.save); qui solo le azioni.
case "freebids.run":
{
if (world.FreeBids is not { } fb) return new Ack(false, "Il riscatto esiste solo sul sito vero, non nel simulatore");
_ = Task.Run(() => fb.RunOnceAsync(manual: true, world.Token), world.Token);
return new Ack(true, "Giro avviato: l'esito compare nel registro della pagina");
}
case "freebids.redeem":
{
if (world.FreeBids is not { } fb) return new Ack(false, "Il riscatto esiste solo sul sito vero, non nel simulatore");
var link = Str(m, "link") ?? "";
var message = await fb.RedeemPastedAsync(link, world.Token).ConfigureAwait(false);
return new Ack(!message.StartsWith("Collegamento non valido", StringComparison.Ordinal), message);
}
case "freebids.resume":
{
if (world.FreeBids is not { } fb) return new Ack(false, "Il riscatto esiste solo sul sito vero, non nel simulatore");
fb.Resume();
return new Ack(true, "Pausa tolta: il prossimo giro apre un collegamento solo finché il saldo non conferma");
}
default:
return new Ack(false, $"Comando sconosciuto: {t}");
}
+2
View File
@@ -219,6 +219,7 @@ public sealed partial class WebSocketHub : IAsyncDisposable
Block(outgoing, "mode", Views.Mode(settings, world));
// L'esportazione: a ogni giro mentre è in corso (cambia solo se avanza), così la barra si muove.
Block(outgoing, "export", Views.Export(_bot.ExportJobs.Current));
Block(outgoing, "freebids", Views.FreeBids(world.FreeBids));
if (_tick % 20 == 0)
{
Block(outgoing, "net", Views.Net(world), ignore: "nowUnixMs");
@@ -325,6 +326,7 @@ public sealed partial class WebSocketHub : IAsyncDisposable
["net"] = Views.Net(world),
["db"] = Views.Db(_bot.Queue, _bot.Maintenance),
["export"] = Views.Export(_bot.ExportJobs.Current),
["freebids"] = Views.FreeBids(world?.FreeBids),
["log"] = _bot.Log.Snapshot(200).Select(EventMessage).ToList()
};
}
+1
View File
@@ -15,6 +15,7 @@ const pages = [
{ id: 'prodotti', label: 'Prodotti', ic: 'star', title: 'Schede dei prodotti: paletti scritti e calcolati, valore reale, prodotti seguiti, statistiche', load: () => import('./pages/prodotti.js') },
{ id: 'storico', label: 'Storico', ic: 'history', title: 'Le aste concluse, con il perché e le esportazioni CSV', load: () => import('./pages/storico.js') },
{ id: 'apprendimento', label: 'Apprendimento', ic: 'chart', title: 'Cosa ha imparato il modello e quanto rende', load: () => import('./pages/apprendimento.js') },
{ id: 'puntate-gratis', label: 'Puntate gratis', ic: 'gift', title: 'Riscatto automatico delle puntate gratuite, forzieri e registro delle operazioni', load: () => import('./pages/puntate-gratis.js') },
{ id: 'browser', label: 'Browser', ic: 'globe', title: 'Il browser del bot: naviga dentro Bidoo, accedi con il tuo utente, aggiungi un\'asta al monitor', load: () => import('./pages/browser.js') },
{ id: 'impostazioni', label: 'Impostazioni', ic: 'gear', title: 'Paletti, rischio, puntate, apprendimento, rete, Telegram, dati', load: () => import('./pages/impostazioni.js') },
{ id: 'registro', label: 'Registro', ic: 'log', title: 'Il registro dell\'applicazione, con filtri', load: () => import('./pages/registro.js'), hidden: true }
+1
View File
@@ -20,6 +20,7 @@ const paths = {
globe: '<circle cx="12" cy="12" r="8.5"/><path d="M3.5 12h17M12 3.5c2.5 2.6 3.5 5.4 3.5 8.5s-1 5.9-3.5 8.5c-2.5-2.6-3.5-5.4-3.5-8.5s1-5.9 3.5-8.5z"/>',
gavel: '<path d="M13 4l7 7M10.5 6.5l7 7M9 8l7 7M15.5 9.5L6 19a1.4 1.4 0 0 1-2-2l9.5-9.5"/>',
search: '<circle cx="10.5" cy="10.5" r="6"/><path d="M15 15l5.5 5.5"/>',
gift: '<rect x="4" y="9" width="16" height="11" rx="1"/><path d="M3 9h18M12 9v11"/><path d="M12 9c-1.5-3.5-5.5-4-5.5-1.5S10 9 12 9zM12 9c1.5-3.5 5.5-4 5.5-1.5S14 9 12 9z"/>',
star: '<path d="M12 3.5l2.6 5.3 5.9.9-4.3 4.1 1 5.8L12 16.9l-5.2 2.7 1-5.8L3.5 9.7l5.9-.9z"/>',
history: '<path d="M4 12a8 8 0 1 0 2.4-5.7L4 8.5"/><path d="M4 4v4.5h4.5"/><path d="M12 8v4.5l3 2"/>',
chart: '<path d="M4 19h16"/><path d="M6.5 15l4-5 3 3 4.5-6"/>',
@@ -81,6 +81,20 @@ const sections = [
['CatalogCacheSeconds', 'Catalogo: cache s', I, 'Per quanto una lettura del catalogo resta buona'],
['CatalogMaxAuctions', 'Catalogo: aste per categoria', I, 'Quante aste si leggono al massimo per ogni categoria del catalogo']
] },
{ title: 'Puntate gratis', hint: 'Riscatto automatico dei collegamenti promozionali e avviso dei forzieri', note: 'Si accendono dalla pagina Puntate gratis. Finché il primo accredito non è confermato dal saldo si apre un collegamento per giro; una risposta strana di Bidoo mette il riscatto in pausa.', fields: [
['FreeBidsEnabled', 'Riscatto automatico', B, 'Spento di fabbrica: a ogni giro il bot riscatta i collegamenti nuovi con il tuo utente'],
['FreeBidsIntervalMinutes', 'Un giro ogni min', I, 'Minimo 10, più una pausa casuale fino a 2 minuti'],
['FreeBidsMaxPerRun', 'Collegamenti per giro', I, '0 = nessun limite'],
['FreeBidsMaxPerDay', 'Riscatti al giorno', I, '0 = nessun limite'],
['FreeBidsMaxAttempts', 'Tentativi per codice', I, 'Per un codice senza esito definitivo (rete, richiesta rifiutata); mai dentro lo stesso giro'],
['FreeBidsPauseMinSeconds', 'Pausa fra riscatti: da s', I, 'Pausa casuale fra un riscatto e il successivo, minimo 2'],
['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)'],
['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']
] },
{ title: 'Telegram', hint: 'Notifiche e comandi su Telegram', telegram: true, fields: [
['TelegramBotToken', 'Token del bot', S, 'Da @BotFather. Resta nel database e in /config/cache (0600), mai nei registri'],
['TelegramChatId', 'Chat ID', T, 'La chat dove arrivano i messaggi (scrivi prima un messaggio al bot)'],
@@ -0,0 +1,220 @@
// Puntate gratis: il riscatto automatico dei collegamenti promozionali (spento di fabbrica), un collegamento
// da incollare, i contatori, e tre schede: puntate riscattate, forzieri, registro delle operazioni.
// Lo stato arriva col blocco «freebids» del WebSocket; gli elenchi con /api/puntate-gratis.
import { el, num, when, time, getJson, report } from '../util.js';
import { state, subscribe, send } from '../state.js';
const outcomes = {
'credited': ['accreditate', 'ok'],
'credited-warning': ['accreditate con avviso', 'warn'],
'already-used': ['già usato', ''],
'expired': ['scaduto', ''],
'not-exists': ['sconosciuto a Bidoo', ''],
'verify': ['verifica richiesta', 'bad'],
'no-session': ['senza sessione', 'bad'],
'refused': ['rifiutato', ''],
'bad-request': ['richiesta rifiutata', 'warn'],
'network': ['nessuna risposta', 'warn'],
'unknown': ['risposta sconosciuta', 'bad']
};
let unsub = [], ui = {}, tab = 'riscatti', data = null, reloadTimer = null;
export async function mount(host) {
ui.enabled = toggle('FreeBidsEnabled', 'Riscatto automatico', 'Acceso: a ogni giro il bot legge i collegamenti nuovi e li riscatta con il tuo utente, entro i tetti delle Impostazioni. Spento di fabbrica.');
ui.chests = toggle('ChestWatchEnabled', 'Avviso forzieri', 'Acceso: a intervalli il bot guarda se in una categoria c\'è un forziere e lo avvisa (registro e Telegram). Non lo apre.');
ui.run = el('button', { class: 'btn primary', type: 'button', title: 'Un giro adesso, anche con il riscatto automatico spento: legge la fonte e riscatta i collegamenti nuovi entro i tetti', onclick: runNow }, 'Esegui ora');
ui.resume = el('button', { class: 'btn', type: 'button', hidden: true, title: 'Togli la pausa: il giro dopo apre un collegamento solo finché il saldo non conferma', onclick: resume }, 'Togli la pausa');
host.append(el('div', { class: 'toolbar' }, el('h1', null, 'Puntate gratis'), ui.enabled.label, ui.chests.label, ui.run, ui.resume,
el('span', { class: 'spacer' }),
el('span', { class: 'sub', title: 'Da dove vengono i collegamenti e come si riscattano' }, 'Collegamenti da puntateaste.it, aperti con il tuo utente di Bidoo. Il saldo conferma ogni accredito.')));
ui.status = el('p', { class: 'help', title: 'Lo stato del riscatto automatico' });
ui.pause = el('p', { class: 'bad', hidden: true, title: 'Perché il riscatto automatico è in pausa' });
ui.counts = el('div', { class: 'grid4' });
ui.link = el('input', { class: 'txt', type: 'url', placeholder: 'https://it.bidoo.com/?promocode=…&sign=…', style: { width: '460px', maxWidth: '100%' },
title: 'Un collegamento promozionale di Bidoo, intero: si apre così com\'è, una sola volta' });
ui.paste = el('button', { class: 'btn', type: 'button', title: 'Riscatta questo collegamento adesso', onclick: redeemPasted }, 'Riscatta');
ui.pasteResult = el('span', { class: 'sub', title: 'Esito dell\'ultimo collegamento incollato' });
ui.link.addEventListener('keydown', e => { if (e.key === 'Enter') redeemPasted(); });
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('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' } });
host.append(el('div', { class: 'page' },
el('section', { class: 'section' }, el('h2', null, 'Stato'), el('div', { class: 'in' }, ui.status, ui.pause, ui.counts)),
el('section', { class: 'section' }, el('h2', null, 'Incolla un collegamento'),
el('div', { class: 'in' }, el('div', { class: 'toolbar' }, ui.link, ui.paste, ui.pasteResult))),
el('section', { class: 'section' }, ui.tabs, ui.body)));
unsub.push(subscribe('freebids', paint));
paint(state.freebids);
await load();
}
export function unmount() {
for (const u of unsub) u();
unsub = [];
clearTimeout(reloadTimer);
ui = {};
data = null;
}
function toggle(key, text, title) {
const input = el('input', { type: 'checkbox', title });
input.addEventListener('change', async () => {
input.disabled = true;
const ack = await send({ t: 'settings.save', patch: { [key]: input.checked } });
input.disabled = false;
if (!ack?.ok) input.checked = !input.checked;
report(ack);
});
return { key, input, label: el('label', { title, style: { display: 'inline-flex', alignItems: 'center', gap: '6px' } },
el('span', { class: 'switch' }, input, el('span')), text) };
}
function tabButton(id, text, title) {
return el('button', { class: id === tab ? 'on' : '', type: 'button', role: 'tab', 'data-tab': id, title,
onclick: () => { tab = id; for (const b of ui.tabs.children) b.classList.toggle('on', b.dataset.tab === id); paintBody(); } }, text);
}
function paintToggles() {
const f = state.freebids || {};
if (ui.enabled && !ui.enabled.input.disabled) ui.enabled.input.checked = !!f.enabled;
if (ui.chests && !ui.chests.input.disabled) ui.chests.input.checked = !!f.chestWatch;
}
let lastLogTop = null;
function paint(f) {
if (!ui.status || !f) return;
paintToggles();
if (f.present === false) {
ui.status.textContent = 'Il riscatto esiste solo sul sito vero: nel simulatore non c\'è.';
for (const c of [ui.enabled.input, ui.chests.input, ui.run, ui.paste]) c.disabled = true;
return;
}
const parts = [];
parts.push(f.enabled ? 'Riscatto automatico acceso' : 'Riscatto automatico spento');
if (!f.available) parts.push(f.unavailable || 'non disponibile');
if (f.running) parts.push('giro in corso');
if (f.lastRunAt) parts.push('ultimo giro ' + when(f.lastRunAt));
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)}` : ''));
ui.status.textContent = parts.join(' · ');
if (f.lastSummary) ui.status.title = 'Ultimo giro: ' + f.lastSummary;
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.';
ui.run.disabled = !!f.running || !f.available;
ui.paste.disabled = !f.available;
// Una riga nuova nel registro: si rileggono gli elenchi (poco dopo, una volta sola).
const top = f.log && f.log[0] ? f.log[0].at + f.log[0].text : null;
if (top !== lastLogTop) {
const first = lastLogTop === null;
lastLogTop = top;
if (!first) { clearTimeout(reloadTimer); reloadTimer = setTimeout(load, 1500); }
}
}
async function load() {
try {
data = await getJson('/api/puntate-gratis');
} catch (e) {
if (ui.body) ui.body.replaceChildren(el('span', { class: 'bad' }, 'Elenchi non letti: ' + e.message));
return;
}
if (!ui.counts) return;
const c = data.counts || {};
ui.counts.replaceChildren(
kpi('Oggi', c.today, c.todayBids, 'Riscatti riusciti oggi (ora di Roma) e puntate guadagnate secondo il saldo'),
kpi('7 giorni', c.week, c.weekBids, 'Riscatti riusciti negli ultimi 7 giorni e puntate guadagnate secondo il saldo'),
kpi('Totale', c.all, c.allBids, 'Tutti i riscatti riusciti e le puntate guadagnate secondo il saldo'),
el('div', { class: 'stat', title: 'Tutti i tentativi registrati, riusciti o no' },
el('div', { class: 'l' }, 'Tentativi'), el('div', { class: 'v' }, num(c.attempts)), el('div', { class: 's' }, 'riusciti o no')));
paintBody();
}
function kpi(label, count, bids, title) {
return el('div', { class: 'stat', title },
el('div', { class: 'l' }, label), el('div', { class: 'v' }, num(count)), el('div', { class: 's' }, `riscatti, +${num(bids)} puntate`));
}
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 ui.body.replaceChildren(logLines(data.log || []));
}
function th(text, title, cls) { return el('th', { title, class: cls }, text); }
function redemptions(rows) {
if (!rows.length) return el('span', { class: 'help' }, 'Nessun riscatto ancora.');
return el('table', { class: 'grid' },
el('thead', null, el('tr', null,
th('Quando', 'Ora del riscatto'), th('Codice', 'Il codice promozionale'), th('Fonte', 'Da dove viene il collegamento'),
th('Esito', 'La risposta di Bidoo al secondo passo'), th('Dichiarate', 'Puntate dichiarate dalla fonte (indicative)', 'num'),
th('Saldo prima', 'Il saldo prima del riscatto', 'num'), th('Saldo dopo', 'Il saldo dato da Bidoo nella risposta', 'num'),
th('Guadagnate', 'Differenza del saldo: le puntate arrivate davvero', 'num'), th('Nota', 'Avviso di Bidoo o risposta grezza'))),
el('tbody', null, rows.map(r => {
const [text, cls] = outcomes[r.outcome] || [r.outcome, ''];
return el('tr', null,
el('td', { title: when(r.at) }, time(r.at)),
el('td', { title: r.manual ? 'Collegamento incollato a mano' : 'Collegamento della fonte' }, r.code),
el('td', null, r.source),
el('td', { class: cls, title: r.response || '' }, text),
el('td', { class: 'num' }, r.declared == null ? '' : num(r.declared)),
el('td', { class: 'num' }, r.before == null ? '' : num(r.before)),
el('td', { class: 'num' }, r.after == null ? '' : num(r.after)),
el('td', { class: 'num ' + (r.gained > 0 ? 'ok' : '') }, r.gained == null ? '' : (r.gained > 0 ? '+' : '') + num(r.gained)),
el('td', { class: 'sub' }, r.note || ''));
})));
}
function chests(rows) {
if (!rows.length) return el('span', { class: 'help' }, state.freebids?.chestWatch ? 'Nessun forziere visto finora.' : 'Avviso forzieri spento: accendilo in alto per guardare le categorie.');
return el('table', { class: 'grid' },
el('thead', null, el('tr', null, th('Visto', 'La prima volta che il bot l\'ha visto'), th('Fino a', 'L\'ultima volta che il bot l\'ha visto'),
th('Categoria', 'Il tag della categoria di Bidoo', 'num'), th('Indirizzo', 'Dove porta il forziere: si apre a mano'))),
el('tbody', null, rows.map(r => el('tr', null,
el('td', { title: when(r.first) }, time(r.first)), el('td', { title: when(r.last) }, time(r.last)),
el('td', { class: 'num' }, num(r.tag)),
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 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' } },
rows.map(r => el('div', null, el('b', { title: when(r.at) }, time(r.at)), ' ', r.text)));
}
async function runNow() {
ui.run.disabled = true;
const ack = await send({ t: 'freebids.run' });
report(ack);
if (!ack?.ok) ui.run.disabled = false;
}
async function resume() {
report(await send({ t: 'freebids.resume' }));
}
async function redeemPasted() {
const link = ui.link.value.trim();
if (!link) { ui.link.focus(); return; }
ui.paste.disabled = true;
ui.pasteResult.textContent = 'Riscatto in corso…';
const ack = await send({ t: 'freebids.redeem', link }, 60000);
ui.paste.disabled = false;
ui.pasteResult.textContent = ack?.msg || '';
ui.pasteResult.className = 'sub ' + (ack?.ok ? '' : 'bad');
if (ack?.ok) ui.link.value = '';
await load();
}
+3 -2
View File
@@ -16,6 +16,7 @@ export const state = {
net: {},
db: {},
export: {}, // l'esportazione in corso o l'ultima (ExportJobs)
freebids: {}, // il riscatto delle puntate gratuite (FreeBidsService)
log: [],
hello: null,
offsetMs: 0, // ora di Bidoo = Date.now() + offsetMs
@@ -65,7 +66,7 @@ conn.on('snapshot', m => {
state.auctions.clear();
state.order = [];
for (const a of m.auctions || []) { state.auctions.set(a.id, a); state.order.push(a.id); }
for (const k of ['account', 'session', 'risk', 'mode', 'net', 'db', 'export']) {
for (const k of ['account', 'session', 'risk', 'mode', 'net', 'db', 'export', 'freebids']) {
if (m[k]) { state[k] = m[k]; if (k === 'net') clock(m[k]); publish(k, state[k]); }
}
state.log = (m.log || []).slice(-300);
@@ -92,7 +93,7 @@ conn.on('auction.removed', m => {
publish('auction.removed', m.id);
});
for (const k of ['account', 'session', 'risk', 'mode', 'net', 'db', 'export']) {
for (const k of ['account', 'session', 'risk', 'mode', 'net', 'db', 'export', 'freebids']) {
conn.on(k, m => {
const { t, ...rest } = m;
state[k] = rest;
+417
View File
@@ -0,0 +1,417 @@
using System.Net;
using System.Text;
using Mimante.Bidoo;
using Mimante.Bidoo.FreeBids;
using Mimante.Net;
using Mimante.Settings;
using Xunit;
namespace Mimante.Tests;
/// <summary>La fonte dei collegamenti (puntateaste.it): record presi da una risposta vera.</summary>
public class PromoFeedTests
{
internal const string Sample = """
[{"id":27913,"link":"https://it.bidoo.com/?promocode=it_241126_h0900_200manualida500p_5b&amp;sign=55013c4fb4ce74562888c01dec5a1dc9ac4ed275","type":1,"fast":0,"short_link":"","punti":5,"approved":1,"time":1795509322},
{"id":27912,"link":"https://it.bidoo.com/?promocode=2bidsnott231126&amp;sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608","type":1,"fast":1,"short_link":"","punti":2,"approved":1,"time":1795467504},
{"id":27911,"link":"<b>https://it.bidoo.com/?promocode=8bidsmatt231126&amp;sign=b180bc742303c412dc07075be1fed4783dedc2b4</b>","type":1,"fast":0,"short_link":"","punti":"8","approved":1,"time":1795421879},
{"id":27910,"link":"https://it.bidoo.com/?promocode=x&amp;sign=1","type":1,"fast":0,"short_link":"","punti":1,"approved":0,"time":1795421000},
{"id":27909,"link":"","short_link":"https://bit.ly/abc","punti":3,"approved":1,"time":1795420000},
"rotto"]
""";
[Fact]
public void Legge_i_record_veri_e_salta_quelli_non_approvati()
{
var r = PromoFeed.Parse(Sample);
Assert.Null(r.Error);
Assert.Equal(4, r.Items.Count);
Assert.Equal(2, r.Skipped);
var first = r.Items[0];
Assert.Equal(27913, first.SourceId);
Assert.Equal("https://it.bidoo.com/?promocode=it_241126_h0900_200manualida500p_5b&sign=55013c4fb4ce74562888c01dec5a1dc9ac4ed275", first.Link);
Assert.Equal(5, first.Points);
Assert.False(first.Fast);
Assert.Equal(1795509322, first.AddedUnix);
Assert.True(r.Items[1].Fast);
// I marcatori HTML (collegamenti scritti dagli utenti) si tolgono; un numero in una stringa si legge.
Assert.StartsWith("https://it.bidoo.com/?promocode=8bidsmatt231126&sign=", r.Items[2].Link);
Assert.Equal(8, r.Items[2].Points);
// Il collegamento accorciato passa di qui ma il controllo lo scarta.
Assert.Equal("https://bit.ly/abc", r.Items[3].Link);
}
[Theory]
[InlineData("")]
[InlineData("<html>pagina</html>")]
[InlineData("{\"error\":1}")]
public void Una_risposta_diversa_dice_che_il_formato_e_cambiato(string body)
{
var r = PromoFeed.Parse(body);
Assert.Empty(r.Items);
Assert.NotNull(r.Error);
}
[Fact]
public void Il_giorno_si_chiede_con_la_mezzanotte_di_Roma()
{
var rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
// 24/11/2026 00:00 a Roma = 23/11/2026 23:00 UTC.
Assert.Equal("s=1&l=1795474800", PromoFeed.Body("s=1&l={midnight}", new DateOnly(2026, 11, 24), rome));
// In estate l'ora legale: 01/07/2026 00:00 a Roma = 30/06/2026 22:00 UTC.
Assert.Equal("s=1&l=1782856800", PromoFeed.Body("s=1&l={midnight}", new DateOnly(2026, 7, 1), rome));
}
}
/// <summary>Il controllo di un collegamento prima di aprirlo con la sessione di Bidoo.</summary>
public class PromoLinkCheckTests
{
private static readonly string[] Paths = { "/", "/index.php" };
private static PromoLinkCheck.Verdict Check(string url) => PromoLinkCheck.Check(url, "it.bidoo.com", Paths);
[Theory]
[InlineData("https://it.bidoo.com/?promocode=2bidsnott231126&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", "2bidsnott231126")]
[InlineData("https://IT.BIDOO.COM/index.php?promocode=it_231126_h2100_benzina_1b&sign=1c53d8e18d6aa1557e130df63ca9eaf3cb089b22", "it_231126_h2100_benzina_1b")]
[InlineData("https://it.bidoo.com/?sign=1c53d8e18d6aa1557e130df63ca9eaf3cb089b22&promocode=abc", "abc")]
[InlineData("https://it.bidoo.com/?promocode=it_231126_h2100_benzina_1b&amp;sign=1c53d8e18d6aa1557e130df63ca9eaf3cb089b22", "it_231126_h2100_benzina_1b")]
public void Un_collegamento_di_Bidoo_passa(string url, string code)
{
var v = Check(url);
Assert.True(v.Ok, v.Reason);
Assert.Equal(code, v.Link!.Code);
}
[Fact]
public void La_firma_e_l_indirizzo_restano_come_sono()
{
var v = Check("https://it.bidoo.com/?promocode=abc&sign=DFE6423341b5bd16c9e08ac0ded51cc8de0b4608");
Assert.Equal("DFE6423341b5bd16c9e08ac0ded51cc8de0b4608", v.Link!.Sign);
Assert.Equal("https://it.bidoo.com/?promocode=abc&sign=DFE6423341b5bd16c9e08ac0ded51cc8de0b4608", v.Link.Url.OriginalString);
}
[Theory]
[InlineData("http://it.bidoo.com/?promocode=abc&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", "https")]
[InlineData("https://it.bidoo.com.altro.it/?promocode=abc&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", "non è di")]
[InlineData("https://it-bidoo.com/?promocode=abc&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", "non è di")]
[InlineData("https://bit.ly/abc", "non è di")]
[InlineData("https://it.bidoo.com:8443/?promocode=abc&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", "porta")]
[InlineData("https://utente@it.bidoo.com/?promocode=abc&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", "utente")]
[InlineData("https://it.bidoo.com/logout.php?promocode=abc&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", "percorso")]
[InlineData("https://it.bidoo.com/?promocode=abc&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608&redirect=https://x.it", "parametro non ammesso")]
[InlineData("https://it.bidoo.com/?promocode=abc&promocode=def&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", "ripetuto")]
[InlineData("https://it.bidoo.com/?sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", "manca promocode")]
[InlineData("https://it.bidoo.com/?promocode=abc", "manca sign")]
[InlineData("https://it.bidoo.com/?promocode=a%20b&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", "caratteri")]
[InlineData("https://it.bidoo.com/?promocode=abc&sign=zz'or'1", "sign non valida")]
[InlineData("javascript:alert(1)", "https")]
[InlineData("non un indirizzo", "non è un indirizzo")]
[InlineData("", "vuoto")]
public void Tutto_il_resto_si_scarta_con_il_motivo(string url, string reason)
{
var v = Check(url);
Assert.False(v.Ok);
Assert.Contains(reason, v.Reason);
}
[Fact]
public void I_parametri_in_piu_passano_solo_se_ammessi()
{
const string url = "https://it.bidoo.com/?promocode=abc&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608&kp=&by=x";
Assert.False(PromoLinkCheck.Check(url, "it.bidoo.com", Paths).Ok);
Assert.True(PromoLinkCheck.Check(url, "it.bidoo.com", Paths, new[] { "kp", "by" }).Ok);
}
}
/// <summary>La risposta del secondo passo (<c>push_promotions.php</c>), con le forme viste dal vivo.</summary>
public class PromoResponseTests
{
private static readonly RedeemGrammar G = new();
[Theory]
[InlineData(200, "ok-1506", RedeemOutcome.Credited, 1506)]
[InlineData(200, " ok-1.506\n", RedeemOutcome.Credited, 1506)]
[InlineData(200, "clicked", RedeemOutcome.AlreadyUsed, null)]
[InlineData(200, "no", RedeemOutcome.NotExists, null)]
[InlineData(200, "showVerify", RedeemOutcome.VerifyRequired, null)]
[InlineData(200, "<html>home</html>", RedeemOutcome.Unknown, null)]
[InlineData(200, "", RedeemOutcome.Unknown, null)]
[InlineData(400, "bad request", RedeemOutcome.BadRequest, null)]
[InlineData(401, "", RedeemOutcome.NoSession, null)]
[InlineData(403, "", RedeemOutcome.Refused, null)]
[InlineData(500, "", RedeemOutcome.Unknown, null)]
[InlineData(null, "", RedeemOutcome.NetworkError, null)]
public void Ogni_risposta_ha_il_suo_esito(int? status, string body, RedeemOutcome outcome, int? balance)
{
var r = PromoResponse.Parse(status, body, G);
Assert.Equal(outcome, r.Outcome);
Assert.Equal(balance, r.Balance);
}
[Fact]
public void La_scadenza_si_legge_in_ora_UTC()
{
var r = PromoResponse.Parse(200, "expired-1795509322", G);
Assert.Equal(RedeemOutcome.Expired, r.Outcome);
Assert.Equal(DateTimeOffset.FromUnixTimeSeconds(1795509322).UtcDateTime, r.ExpiredUtc);
Assert.True(r.Final);
Assert.False(r.Pause);
}
[Fact]
public void L_avviso_sulla_provenienza_accredita_ma_ferma_il_riscatto()
{
var note = Convert.ToBase64String(Encoding.UTF8.GetBytes("""{"title":"<b>Attenzione</b>","subtitle":"Codice da fonte non ufficiale"}"""));
var r = PromoResponse.Parse(200, $"warningOrigin-50-{note}", G);
Assert.Equal(RedeemOutcome.CreditedWithWarning, r.Outcome);
Assert.Equal(50, r.Balance);
Assert.Equal("Attenzione - Codice da fonte non ufficiale", r.Warning);
Assert.True(r.Final);
Assert.True(r.Pause);
// Un avviso che non si legge non fa cadere nulla.
Assert.Null(PromoResponse.Parse(200, "warningOrigin-50-%%%", G).Warning);
}
[Fact]
public void Quali_esiti_chiudono_il_codice_e_quali_fermano_il_riscatto()
{
static RedeemResult R(int? s, string b) => PromoResponse.Parse(s, b, G);
Assert.True(R(200, "ok-10").Final);
Assert.True(R(200, "clicked").Final);
Assert.True(R(200, "no").Final);
Assert.True(R(403, "").Final);
// Si riprovano al giro dopo: la richiesta rifiutata, la rete, la sessione.
Assert.False(R(400, "").Final);
Assert.False(R(null, "").Final);
Assert.False(R(401, "").Final);
Assert.True(R(200, "showVerify").Pause);
Assert.True(R(200, "qualcosa di nuovo").Pause);
Assert.True(R(401, "").Pause);
Assert.False(R(200, "ok-10").Pause);
Assert.False(R(200, "clicked").Pause);
}
[Fact]
public void Le_parole_vengono_dai_riferimenti()
{
var g = new RedeemGrammar { CreditedPrefix = "fatto:", AlreadyUsed = "usato" };
Assert.Equal(RedeemOutcome.Credited, PromoResponse.Parse(200, "fatto:12", g).Outcome);
Assert.Equal(RedeemOutcome.AlreadyUsed, PromoResponse.Parse(200, "usato", g).Outcome);
Assert.Equal(RedeemOutcome.Unknown, PromoResponse.Parse(200, "ok-12", g).Outcome);
}
}
/// <summary>
/// Un Bidoo finto per i due passi: <c>push_promotions.php</c> risponde 400 se la pagina del codice non è stata aperta
/// prima con la sessione (com'è dal vivo), o se il secondo passo si ripete.
/// </summary>
internal sealed class PromoSite : HttpMessageHandler
{
public readonly List<HttpRequestMessage> Requests = new();
public readonly List<string?> Cookies = new();
private readonly HashSet<string> _opened = new(StringComparer.Ordinal);
private readonly HashSet<string> _answered = new(StringComparer.Ordinal);
public string Answer = "ok-1506";
public HttpStatusCode PageStatus = HttpStatusCode.OK;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
Requests.Add(request);
Cookies.Add(request.Headers.TryGetValues("Cookie", out var c) ? string.Join("; ", c) : null);
var url = request.RequestUri!;
var q = System.Web.HttpUtility.ParseQueryString(url.Query);
if (url.AbsolutePath == "/push_promotions.php")
{
var code = q["code"] ?? "";
if (!_opened.Contains(code) || !_answered.Add(code)) return Text(HttpStatusCode.BadRequest, "bad request");
return Text(HttpStatusCode.OK, Answer);
}
if (url.AbsolutePath == "/ajax/chest/get_chest_tag_url.php")
return Text(HttpStatusCode.OK, q["tag"] == "7" ? """{"url":"https://it.bidoo.com/chest.php?k=abc"}""" : """{"url":null}""");
if (q["promocode"] is { } promo && request.Headers.Contains("Cookie") && !request.Headers.Contains("X-Requested-With"))
_opened.Add(promo);
return Text(PageStatus, "<html><body><div id=\"NickLoggato\">io</div>home</body></html>");
}
private static Task<HttpResponseMessage> Text(HttpStatusCode s, string body) =>
Task.FromResult(new HttpResponseMessage(s) { Content = new StringContent(body) });
}
public class RedeemFlowTests
{
private static readonly PromoLink Link = PromoLinkCheck.Check(
"https://it.bidoo.com/?promocode=2bidsnott231126&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", "it.bidoo.com", new[] { "/" }).Link!;
private static (BidooApi Api, BidooTransport Transport) Make(PromoSite site, bool withSession = true)
{
var refs = BidooReferences.Parse("{}");
var transport = new BidooTransport(() => refs, 0, site);
if (withSession) transport.SetSession("PHPSESSID=abc", null);
return (new BidooApi(transport, new BidLane(transport, () => refs, keepWarm: false), () => refs), transport);
}
[Fact]
public async Task I_due_passi_vanno_in_ordine_e_il_secondo_da_l_esito()
{
var site = new PromoSite();
var (api, transport) = Make(site);
using var _ = transport;
var r = await api.RedeemPromoAsync(Link, CancellationToken.None);
Assert.Equal(RedeemOutcome.Credited, r.Result.Outcome);
Assert.Equal(1506, r.Result.Balance);
Assert.Equal(2, site.Requests.Count);
// Passo 1: il collegamento così com'è, come documento, con la sessione, senza l'intestazione AJAX.
Assert.Equal(Link.Url.OriginalString, site.Requests[0].RequestUri!.OriginalString);
Assert.False(site.Requests[0].Headers.Contains("X-Requested-With"));
Assert.Equal("PHPSESSID=abc", site.Cookies[0]);
// Passo 2: push_promotions con codice e firma, AJAX, con il collegamento come provenienza.
Assert.Equal("/push_promotions.php", site.Requests[1].RequestUri!.AbsolutePath);
Assert.Contains("code=2bidsnott231126&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", site.Requests[1].RequestUri!.Query);
Assert.True(site.Requests[1].Headers.Contains("X-Requested-With"));
Assert.Equal(Link.Url.OriginalString, site.Requests[1].Headers.Referrer!.OriginalString);
// Ripetere la coppia: Bidoo risponde 400 al secondo passo ripetuto, ed è un esito da riprovare, non definitivo.
var again = await api.RedeemPromoAsync(Link, CancellationToken.None);
Assert.Equal(RedeemOutcome.BadRequest, again.Result.Outcome);
Assert.False(again.Result.Final);
}
[Fact]
public async Task Senza_sessione_il_primo_passo_non_apre_il_codice()
{
var site = new PromoSite();
var (api, transport) = Make(site, withSession: false);
using var _ = transport;
Assert.Equal(RedeemOutcome.BadRequest, (await api.RedeemPromoAsync(Link, CancellationToken.None)).Result.Outcome);
}
[Fact]
public async Task Un_errore_della_pagina_non_fa_partire_il_secondo_passo_e_non_scade_la_sessione()
{
var site = new PromoSite { PageStatus = HttpStatusCode.Forbidden };
var (api, transport) = Make(site);
using var _ = transport;
var invalid = false;
api.SessionInvalid += _ => invalid = true;
var r = await api.RedeemPromoAsync(Link, CancellationToken.None);
Assert.Equal(RedeemOutcome.Refused, r.Result.Outcome);
Assert.Single(site.Requests);
Assert.False(invalid);
}
[Fact]
public async Task La_fonte_esterna_non_riceve_mai_il_cookie_di_Bidoo()
{
var site = new PromoSite();
using var external = new ExternalHttp(site);
var answer = await external.PostFormAsync("https://puntateaste.it/index.php", "s=1&l=1795474800", "https://puntateaste.it/", "UA", CancellationToken.None);
Assert.True(answer.Success);
Assert.Null(site.Cookies.Single());
Assert.Equal(HttpMethod.Post, site.Requests.Single().Method);
}
[Fact]
public async Task Il_forziere_di_una_categoria_si_legge()
{
var site = new PromoSite();
var (api, transport) = Make(site);
using var _ = transport;
Assert.Equal("https://it.bidoo.com/chest.php?k=abc", (await api.ProbeChestAsync(7, CancellationToken.None)).Url);
var none = await api.ProbeChestAsync(6, CancellationToken.None);
Assert.True(none.Ok);
Assert.Null(none.Url);
Assert.False(BidooApi.ParseChest("<html>").Ok);
Assert.False(BidooApi.ParseChest("""{"altro":1}""").Ok);
Assert.True(BidooApi.ParseChest("""{"url":""}""").Ok);
}
[Fact]
public void I_riferimenti_di_fabbrica_hanno_la_sezione_del_riscatto()
{
var refs = BidooReferences.Parse("{}");
Assert.Equal("it.bidoo.com", refs.Host);
Assert.Equal("https://puntateaste.it/index.php", refs.FreeBids.FeedUrl);
Assert.Contains("/", refs.FreeBids.PromoPaths);
Assert.StartsWith("/push_promotions.php?", refs.FreeBids.Redeem);
Assert.Equal("ok-", refs.FreeBids.Grammar.CreditedPrefix);
Assert.Equal(20, refs.FreeBids.ChestTags.Count);
var mine = BidooReferences.Parse("""{"freeBids": {"grammar": {"alreadyUsed": "usato"}}}""");
Assert.Equal("usato", mine.FreeBids.Grammar.AlreadyUsed);
Assert.Equal("ok-", mine.FreeBids.Grammar.CreditedPrefix);
}
[Theory]
[InlineData(8, 24, 8, true)]
[InlineData(8, 24, 7, false)]
[InlineData(8, 24, 23, true)]
[InlineData(22, 6, 23, true)]
[InlineData(22, 6, 3, true)]
[InlineData(22, 6, 12, false)]
[InlineData(0, 0, 12, true)]
public void Le_ore_del_riscatto(int start, int end, int hour, bool inside)
{
Assert.Equal(inside, FreeBidsService.InHours(new AppSettings { FreeBidsHoursStart = start, FreeBidsHoursEnd = end }, hour));
}
[Fact]
public void Di_fabbrica_il_riscatto_e_spento()
{
var s = new AppSettings();
Assert.False(s.FreeBidsEnabled);
Assert.False(s.ChestWatchEnabled);
}
}
/// <summary>Quali collegamenti aprire in un giro.</summary>
public class RedeemPlannerTests
{
private static RedeemCandidate C(string code, long added, bool fast = false) =>
new(new PromoLink(code, "dfe6423341b5bd16c9e08ac0ded51cc8de0b4608", new Uri($"https://it.bidoo.com/?promocode={code}&sign=dfe6423341b5bd16c9e08ac0ded51cc8de0b4608")),
"puntateaste", 1, fast, added);
private static readonly RedeemLimits Limits = new(MaxPerRun: 3, MaxPerDay: 10, MaxAttempts: 3);
private static readonly Dictionary<string, KnownCode> None = new();
[Fact]
public void Finche_il_primo_accredito_non_e_confermato_se_ne_apre_uno()
{
var plan = RedeemPlanner.Choose(new[] { C("a", 1), C("b", 3), C("c", 2) }, None, Limits, 0, confirmed: false, paused: false);
Assert.Equal(new[] { "b" }, plan.Open.Select(c => c.Link.Code));
Assert.Contains("confermato", plan.Why);
}
[Fact]
public void Prima_quelli_a_tempo_poi_i_piu_nuovi_entro_il_tetto_del_giro()
{
var plan = RedeemPlanner.Choose(new[] { C("a", 1), C("b", 3), C("c", 2), C("d", 0, fast: true), C("b", 3) }, None, Limits, 0, true, false);
Assert.Equal(new[] { "d", "b", "c" }, plan.Open.Select(c => c.Link.Code));
}
[Fact]
public void I_codici_consumati_o_oltre_i_tentativi_non_si_riprovano()
{
var known = new Dictionary<string, KnownCode>
{
["a"] = new(1, Final: true), ["b"] = new(3, Final: false), ["c"] = new(2, Final: false)
};
var plan = RedeemPlanner.Choose(new[] { C("a", 3), C("b", 2), C("c", 1) }, known, Limits, 0, true, false);
Assert.Equal(new[] { "c" }, plan.Open.Select(c => c.Link.Code));
}
[Fact]
public void La_pausa_e_il_tetto_del_giorno_fermano_tutto()
{
var many = new[] { C("a", 1), C("b", 2), C("c", 3) };
Assert.Empty(RedeemPlanner.Choose(many, None, Limits, 0, true, paused: true).Open);
Assert.Empty(RedeemPlanner.Choose(many, None, Limits, 10, true, false).Open);
Assert.Single(RedeemPlanner.Choose(many, None, Limits, 9, true, false).Open);
Assert.Equal("nessun collegamento nuovo", RedeemPlanner.Choose(Array.Empty<RedeemCandidate>(), None, Limits, 0, true, false).Why);
}
}