Files
Mimante/src/Mimante/Bidoo/FreeBids/RewardsPages.cs
T
Alby96andClaude Opus 5.5 6cbc5e58b0
verifica / controlli (push) Successful in 51s
verifica / prove (push) Successful in 2m18s
verifica / immagine (push) Successful in 13m9s
Ricompense di Bidoo e campanella come seconda fonte del riscatto (#38)
Il bot riscattava i collegamenti di puntateaste.it ma non sapeva se Bidoo li
avesse accreditati davvero, e perdeva i collegamenti che arrivano solo nella
campanella del sito.

- A intervalli (FreeBidsRewardsHours, 6 ore, 0 = mai) legge /my_chests.php e la
  prima pagina di /bids_history.php, salva le ricompense nuove in
  account_rewards (migrazione 0006, chiave unica, solo inserimenti) e scrive nel
  registro se i conti del giorno con i riscatti del bot tornano.
- La campanella /checkN.php diventa seconda fonte (FreeBidsUseNotifications):
  solo la lettura semplice, mai _d o _r, cosi' le notifiche restano non lette.
- Pagina Puntate gratis: scheda «Ricompense di Bidoo» e ora dell'ultima lettura.
- La tabella entra nello scaricamento dei dati; test con copie della struttura
  vera delle due pagine e della campanella, valori inventati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:48:05 +01:00

195 lines
12 KiB
C#

using System.Globalization;
using System.Net;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Mimante.Bidoo.FreeBids;
/// <summary>
/// Una ricompensa che Bidoo ha accreditato davvero: un forziere (<c>/my_chests.php</c>) o un movimento della
/// cronologia crediti (<c>/bids_history.php</c>). <paramref name="Key"/> la rende unica in <c>account_rewards</c>.
/// <paramref name="Source"/>: per i forzieri come sono stati ottenuti («link», «aste di puntate confermate»…).
/// </summary>
public sealed record AccountReward(string Key, string Kind, DateTime AtUtc, int Bids, bool Free, string Source, string Description);
/// <summary>Quello che si legge da una delle due pagine: le ricompense, o perché non si è letta.</summary>
public sealed record RewardsRead(IReadOnlyList<AccountReward> Items, string? Error, int Skipped = 0);
/// <summary>I collegamenti promozionali trovati nella campanella, con l'id della notifica che li contiene.</summary>
public sealed record NotificationLinks(int Notifications, IReadOnlyList<(string Id, string Href)> Links, string? Error);
/// <summary>
/// Le pagine delle ricompense e la campanella di Bidoo (issue #38). Pure, sotto test con copie della struttura
/// vera (valori inventati). Le date dei forzieri sono scritte in italiano, ora di Roma; quelle della cronologia
/// sono nello script della pagina, in secondi Unix, legate all'id del movimento.
/// </summary>
public static class RewardsPages
{
public const string KindChest = "forziere";
public const string KindCredit = "accredito";
private const RegexOptions Opt = RegexOptions.CultureInvariant | RegexOptions.Singleline | RegexOptions.IgnoreCase;
private static readonly string[] Months =
["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"];
private static readonly Regex ChestItem = new(@"<div\s+class=""wrap-item\b", Opt);
private static readonly Regex ChestText = new(@"<div\s+class=""text"">(.*?)</div>", Opt);
private static readonly Regex ChestPoints = new(@"<div\s+class=""pt-chest"">\s*<b>\s*\+?\s*(\d+)\s*</b>.*?<b>\s*([^<]+?)\s*</b>", Opt);
private static readonly Regex ItalianDate = new(@"(\d{1,2})\s+(" + string.Join('|', Months) + @")\s+(\d{4})(?:\s+alle)?\s+(\d{1,2}):(\d{2})", Opt);
private static readonly Regex ChestSource = new(@"tramite\s+(.+?)\s+il\s+\d", Opt);
private static readonly Regex CreditTable = new(@"<table[^>]*class=""[^""]*my-bidoo-table[^""]*""[^>]*>(.*?)</table>", Opt);
private static readonly Regex Row = new(@"<tr\b[^>]*>(.*?)</tr>", Opt);
private static readonly Regex MovementId = new(@"id=""data_mov(\d+)""", Opt);
private static readonly Regex FirstRow = new(@"<span\s+class=""first_row_desc"">(.*?)</span>", Opt);
private static readonly Regex SecondRow = new(@"<div\s+class=""second_row_desc[^""]*"">(.*?)</div>", Opt);
private static readonly Regex Total = new(@"<td\s+class=""[^""]*\btot\b[^""]*"">(.*?)</td>", Opt);
private static readonly Regex MovementTime = new(@"'data_mov'\s*\+\s*(\d+)\s*\)\s*\)\s*\{[^}]*?formattaDataStorico\(\s*(\d+)", Opt);
private static readonly Regex LeadingNumber = new(@"^\s*(\d[\d.]*)", Opt);
private static readonly Regex Tags = new("<[^>]+>", Opt);
private static readonly Regex Spaces = new(@"\s+", Opt);
private static readonly Regex Href = new(@"href\s*=\s*[""']([^""']+)[""']", Opt);
private static readonly Regex BareUrl = new(@"https?://[^\s""'<>]+", Opt);
// ── /my_chests.php ────────────────────────────────────────────────
/// <summary>
/// I forzieri aperti: ogni <c>wrap-item</c> con il testo («Ottenuto tramite link il 9 Novembre 2026 alle 14:05»)
/// e il premio (<c>pt-chest</c>, «+3 Puntate»). Un forziere senza premio (ancora da aprire o scaduto) si salta.
/// Due forzieri uguali nello stesso minuto restano due: la chiave porta il numero d'ordine.
/// </summary>
public static RewardsRead ParseChests(string? html, TimeZoneInfo tz)
{
if (string.IsNullOrEmpty(html) || !html.Contains("items-sections", StringComparison.OrdinalIgnoreCase))
return new([], "la pagina delle ricompense non ha l'elenco dei forzieri: sessione scaduta o formato cambiato?");
var starts = ChestItem.Matches(html).Select(m => m.Index).ToList();
var items = new List<AccountReward>();
var seen = new Dictionary<string, int>(StringComparer.Ordinal);
var skipped = 0;
for (var i = 0; i < starts.Count; i++)
{
var block = html[starts[i]..(i + 1 < starts.Count ? starts[i + 1] : html.Length)];
var points = ChestPoints.Match(block);
if (!points.Success) continue;
var text = Clean(ChestText.Match(block).Groups[1].Value);
var date = ItalianDate.Match(text);
if (!date.Success) { skipped++; continue; }
var local = new DateTime(int.Parse(date.Groups[3].Value, CultureInfo.InvariantCulture),
Array.IndexOf(Months, date.Groups[2].Value.ToLowerInvariant()) + 1, int.Parse(date.Groups[1].Value, CultureInfo.InvariantCulture),
int.Parse(date.Groups[4].Value, CultureInfo.InvariantCulture), int.Parse(date.Groups[5].Value, CultureInfo.InvariantCulture), 0,
DateTimeKind.Unspecified);
var amount = int.Parse(points.Groups[1].Value, CultureInfo.InvariantCulture);
var unit = Clean(points.Groups[2].Value);
var isBids = unit.StartsWith("puntat", StringComparison.OrdinalIgnoreCase);
var source = ChestSource.Match(text) is { Success: true } s ? Clean(s.Groups[1].Value).ToLowerInvariant() : "";
var baseKey = $"{KindChest}|{local:yyyy-MM-ddTHH:mm}|{source}|{amount} {unit.ToLowerInvariant()}";
var n = seen.GetValueOrDefault(baseKey);
seen[baseKey] = n + 1;
items.Add(new AccountReward($"{baseKey}|{n}", KindChest, ToUtc(local, tz), isBids ? amount : 0, true, source,
$"{text} (+{amount} {unit})"));
}
return new(items, null, skipped);
}
// ── /bids_history.php ─────────────────────────────────────────────
/// <summary>
/// La cronologia crediti: una riga per movimento (<c>data_mov&lt;id&gt;</c>), descrizione («3 Gratis»), totale
/// («Gratis» o un prezzo). L'ora la scrive lo script della pagina: <c>'data_mov' + id … formattaDataStorico(unix</c>.
/// </summary>
public static RewardsRead ParseCreditHistory(string? html)
{
if (string.IsNullOrEmpty(html) || CreditTable.Match(html) is not { Success: true } table)
return new([], "la cronologia crediti non ha la tabella dei movimenti: sessione scaduta o formato cambiato?");
var times = new Dictionary<string, long>(StringComparer.Ordinal);
foreach (Match m in MovementTime.Matches(html))
times[m.Groups[1].Value] = long.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture);
var items = new List<AccountReward>();
var skipped = 0;
foreach (Match row in Row.Matches(table.Groups[1].Value))
{
var cells = row.Groups[1].Value;
if (MovementId.Match(cells) is not { Success: true } id) continue; // l'intestazione
if (!times.TryGetValue(id.Groups[1].Value, out var unix)) { skipped++; continue; }
var first = Clean(FirstRow.Match(cells).Groups[1].Value);
var second = Clean(SecondRow.Match(cells).Groups[1].Value);
var total = Clean(Total.Match(cells).Groups[1].Value);
var bids = LeadingNumber.Match(first) is { Success: true } b
&& int.TryParse(b.Groups[1].Value.Replace(".", ""), NumberStyles.None, CultureInfo.InvariantCulture, out var v) ? v : 0;
var free = total.Contains("gratis", StringComparison.OrdinalIgnoreCase);
var description = string.Join(" · ", new[] { first, second, total }.Where(x => x.Length > 0));
items.Add(new AccountReward($"{KindCredit}|{id.Groups[1].Value}", KindCredit,
DateTimeOffset.FromUnixTimeSeconds(unix).UtcDateTime, bids, free, "", description));
}
return new(items, null, skipped);
}
// ── /checkN.php ───────────────────────────────────────────────────
/// <summary>
/// La campanella: <c>{"count":…, "elements": {…} | […]}</c>, ogni notifica con <c>id</c> e <c>content</c> in HTML.
/// Si tengono solo gli indirizzi con <c>promocode</c>: poi passano dallo stesso controllo dei collegamenti della fonte.
/// </summary>
public static NotificationLinks ParseNotifications(string? json)
{
try
{
using var doc = JsonDocument.Parse(string.IsNullOrWhiteSpace(json) ? "null" : json);
if (doc.RootElement.ValueKind != JsonValueKind.Object || !doc.RootElement.TryGetProperty("elements", out var els))
return new(0, [], "risposta della campanella senza elements: sessione scaduta o formato cambiato?");
var list = els.ValueKind switch
{
JsonValueKind.Array => els.EnumerateArray().ToList(),
JsonValueKind.Object => els.EnumerateObject().Select(p => p.Value).ToList(),
_ => []
};
var links = new List<(string, string)>();
var count = 0;
foreach (var e in list.Where(x => x.ValueKind == JsonValueKind.Object))
{
count++;
var id = e.TryGetProperty("id", out var idv) ? idv.ToString() : "";
var content = e.TryGetProperty("content", out var c) && c.ValueKind == JsonValueKind.String ? c.GetString() ?? "" : "";
var found = Href.Matches(content).Select(m => m.Groups[1].Value)
.Concat(BareUrl.Matches(Tags.Replace(content, " ")).Select(m => m.Value))
.Select(h => WebUtility.HtmlDecode(h) ?? "")
.Where(h => h.Contains("promocode", StringComparison.OrdinalIgnoreCase))
.Distinct(StringComparer.Ordinal);
foreach (var h in found) links.Add((id, h));
}
return new(count, links, null);
}
catch (JsonException)
{
return new(0, [], "la campanella non ha risposto con JSON: sessione scaduta o formato cambiato?");
}
}
// ── confronto ─────────────────────────────────────────────────────
/// <summary>
/// Il confronto del giorno fra ciò che Bidoo segna come ottenuto tramite collegamento e i riscatti riusciti del bot.
/// Una differenza non è per forza un errore: un collegamento aperto a mano dal telefono conta per Bidoo, non per il bot.
/// </summary>
public static string CompareToday(IEnumerable<AccountReward> rewards, DateOnly today, TimeZoneInfo tz, int redeemed, int gained)
{
var fromLinks = rewards.Where(r => r.Kind == KindChest && r.Source == "link"
&& DateOnly.FromDateTime(TimeZoneInfo.ConvertTimeFromUtc(r.AtUtc, tz)) == today).ToList();
var bids = fromLinks.Sum(r => r.Bids);
var head = $"oggi Bidoo segna {fromLinks.Count} ricompense da collegamento (+{bids} puntate), il bot ha {redeemed} riscatti riusciti (+{gained} dal saldo)";
return fromLinks.Count == redeemed && bids == gained ? head + ": tornano"
: fromLinks.Count > redeemed ? head + ": gli altri sono collegamenti aperti fuori dal bot o accrediti non visti dal saldo"
: head + ": qualche riscatto del bot non compare fra le ricompense";
}
private static DateTime ToUtc(DateTime local, TimeZoneInfo tz)
{
try { return TimeZoneInfo.ConvertTimeToUtc(local, tz); }
catch (ArgumentException) { return TimeZoneInfo.ConvertTimeToUtc(local.AddHours(1), tz); } // ora che non esiste (cambio d'ora)
}
private static string Clean(string html) => Spaces.Replace(WebUtility.HtmlDecode(Tags.Replace(html, " ")), " ").Trim();
}