\s*
\s*\+?\s*(\d+)\s*.*?
\s*([^<]+?)\s*", Opt);
private static readonly Regex ItalianDate = new(@"(\d{1,2})\s+(" + string.Join('|', Months) + @")\s+(\d{4})(?:\s+alle)?\s+(\d{1,2}):(\d{2})", Opt);
private static readonly Regex ChestSource = new(@"tramite\s+(.+?)\s+il\s+\d", Opt);
private static readonly Regex CreditTable = new(@"
]*class=""[^""]*my-bidoo-table[^""]*""[^>]*>(.*?)
", Opt);
private static readonly Regex Row = new(@"
]*>(.*?)
", Opt);
private static readonly Regex MovementId = new(@"id=""data_mov(\d+)""", Opt);
private static readonly Regex FirstRow = new(@"
(.*?)", Opt);
private static readonly Regex SecondRow = new(@"
(.*?)
", Opt);
private static readonly Regex Total = new(@"
(.*?) | ", Opt);
private static readonly Regex MovementTime = new(@"'data_mov'\s*\+\s*(\d+)\s*\)\s*\)\s*\{[^}]*?formattaDataStorico\(\s*(\d+)", Opt);
private static readonly Regex LeadingNumber = new(@"^\s*(\d[\d.]*)", Opt);
private static readonly Regex Tags = new("<[^>]+>", Opt);
private static readonly Regex Spaces = new(@"\s+", Opt);
private static readonly Regex Href = new(@"href\s*=\s*[""']([^""']+)[""']", Opt);
private static readonly Regex BareUrl = new(@"https?://[^\s""'<>]+", Opt);
// ── /my_chests.php ────────────────────────────────────────────────
///
/// I forzieri aperti: ogni wrap-item con il testo («Ottenuto tramite link il 9 Novembre 2026 alle 14:05»)
/// e il premio (pt-chest, «+3 Puntate»). Un forziere senza premio (ancora da aprire o scaduto) si salta.
/// Due forzieri uguali nello stesso minuto restano due: la chiave porta il numero d'ordine.
///
public static RewardsRead ParseChests(string? html, TimeZoneInfo tz)
{
if (string.IsNullOrEmpty(html) || !html.Contains("items-sections", StringComparison.OrdinalIgnoreCase))
return new([], "la pagina delle ricompense non ha l'elenco dei forzieri: sessione scaduta o formato cambiato?");
var starts = ChestItem.Matches(html).Select(m => m.Index).ToList();
var items = new List
();
var seen = new Dictionary(StringComparer.Ordinal);
var skipped = 0;
for (var i = 0; i < starts.Count; i++)
{
var block = html[starts[i]..(i + 1 < starts.Count ? starts[i + 1] : html.Length)];
var points = ChestPoints.Match(block);
if (!points.Success) continue;
var text = Clean(ChestText.Match(block).Groups[1].Value);
var date = ItalianDate.Match(text);
if (!date.Success) { skipped++; continue; }
var local = new DateTime(int.Parse(date.Groups[3].Value, CultureInfo.InvariantCulture),
Array.IndexOf(Months, date.Groups[2].Value.ToLowerInvariant()) + 1, int.Parse(date.Groups[1].Value, CultureInfo.InvariantCulture),
int.Parse(date.Groups[4].Value, CultureInfo.InvariantCulture), int.Parse(date.Groups[5].Value, CultureInfo.InvariantCulture), 0,
DateTimeKind.Unspecified);
var amount = int.Parse(points.Groups[1].Value, CultureInfo.InvariantCulture);
var unit = Clean(points.Groups[2].Value);
var isBids = unit.StartsWith("puntat", StringComparison.OrdinalIgnoreCase);
var source = ChestSource.Match(text) is { Success: true } s ? Clean(s.Groups[1].Value).ToLowerInvariant() : "";
var baseKey = $"{KindChest}|{local:yyyy-MM-ddTHH:mm}|{source}|{amount} {unit.ToLowerInvariant()}";
var n = seen.GetValueOrDefault(baseKey);
seen[baseKey] = n + 1;
items.Add(new AccountReward($"{baseKey}|{n}", KindChest, ToUtc(local, tz), isBids ? amount : 0, true, source,
$"{text} (+{amount} {unit})"));
}
return new(items, null, skipped);
}
// ── /bids_history.php ─────────────────────────────────────────────
///
/// La cronologia crediti: una riga per movimento (data_mov<id>), descrizione («3 Gratis»), totale
/// («Gratis» o un prezzo). L'ora la scrive lo script della pagina: 'data_mov' + id … formattaDataStorico(unix.
///
public static RewardsRead ParseCreditHistory(string? html)
{
if (string.IsNullOrEmpty(html) || CreditTable.Match(html) is not { Success: true } table)
return new([], "la cronologia crediti non ha la tabella dei movimenti: sessione scaduta o formato cambiato?");
var times = new Dictionary(StringComparer.Ordinal);
foreach (Match m in MovementTime.Matches(html))
times[m.Groups[1].Value] = long.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture);
var items = new List();
var skipped = 0;
foreach (Match row in Row.Matches(table.Groups[1].Value))
{
var cells = row.Groups[1].Value;
if (MovementId.Match(cells) is not { Success: true } id) continue; // l'intestazione
if (!times.TryGetValue(id.Groups[1].Value, out var unix)) { skipped++; continue; }
var first = Clean(FirstRow.Match(cells).Groups[1].Value);
var second = Clean(SecondRow.Match(cells).Groups[1].Value);
var total = Clean(Total.Match(cells).Groups[1].Value);
var bids = LeadingNumber.Match(first) is { Success: true } b
&& int.TryParse(b.Groups[1].Value.Replace(".", ""), NumberStyles.None, CultureInfo.InvariantCulture, out var v) ? v : 0;
var free = total.Contains("gratis", StringComparison.OrdinalIgnoreCase);
var description = string.Join(" · ", new[] { first, second, total }.Where(x => x.Length > 0));
items.Add(new AccountReward($"{KindCredit}|{id.Groups[1].Value}", KindCredit,
DateTimeOffset.FromUnixTimeSeconds(unix).UtcDateTime, bids, free, "", description));
}
return new(items, null, skipped);
}
// ── /checkN.php ───────────────────────────────────────────────────
///
/// La campanella: {"count":…, "elements": {…} | […]}, ogni notifica con id e content in HTML.
/// Si tengono solo gli indirizzi con promocode: poi passano dallo stesso controllo dei collegamenti della fonte.
///
public static NotificationLinks ParseNotifications(string? json)
{
try
{
using var doc = JsonDocument.Parse(string.IsNullOrWhiteSpace(json) ? "null" : json);
if (doc.RootElement.ValueKind != JsonValueKind.Object || !doc.RootElement.TryGetProperty("elements", out var els))
return new(0, [], "risposta della campanella senza elements: sessione scaduta o formato cambiato?");
var list = els.ValueKind switch
{
JsonValueKind.Array => els.EnumerateArray().ToList(),
JsonValueKind.Object => els.EnumerateObject().Select(p => p.Value).ToList(),
_ => []
};
var links = new List<(string, string)>();
var count = 0;
foreach (var e in list.Where(x => x.ValueKind == JsonValueKind.Object))
{
count++;
var id = e.TryGetProperty("id", out var idv) ? idv.ToString() : "";
var content = e.TryGetProperty("content", out var c) && c.ValueKind == JsonValueKind.String ? c.GetString() ?? "" : "";
var found = Href.Matches(content).Select(m => m.Groups[1].Value)
.Concat(BareUrl.Matches(Tags.Replace(content, " ")).Select(m => m.Value))
.Select(h => WebUtility.HtmlDecode(h) ?? "")
.Where(h => h.Contains("promocode", StringComparison.OrdinalIgnoreCase))
.Distinct(StringComparer.Ordinal);
foreach (var h in found) links.Add((id, h));
}
return new(count, links, null);
}
catch (JsonException)
{
return new(0, [], "la campanella non ha risposto con JSON: sessione scaduta o formato cambiato?");
}
}
// ── confronto ─────────────────────────────────────────────────────
///
/// Il confronto del giorno fra ciò che Bidoo segna come ottenuto tramite collegamento e i riscatti riusciti del bot.
/// Una differenza non è per forza un errore: un collegamento aperto a mano dal telefono conta per Bidoo, non per il bot.
///
public static string CompareToday(IEnumerable rewards, DateOnly today, TimeZoneInfo tz, int redeemed, int gained)
{
var fromLinks = rewards.Where(r => r.Kind == KindChest && r.Source == "link"
&& DateOnly.FromDateTime(TimeZoneInfo.ConvertTimeFromUtc(r.AtUtc, tz)) == today).ToList();
var bids = fromLinks.Sum(r => r.Bids);
var head = $"oggi Bidoo segna {fromLinks.Count} ricompense da collegamento (+{bids} puntate), il bot ha {redeemed} riscatti riusciti (+{gained} dal saldo)";
return fromLinks.Count == redeemed && bids == gained ? head + ": tornano"
: fromLinks.Count > redeemed ? head + ": gli altri sono collegamenti aperti fuori dal bot o accrediti non visti dal saldo"
: head + ": qualche riscatto del bot non compare fra le ricompense";
}
private static DateTime ToUtc(DateTime local, TimeZoneInfo tz)
{
try { return TimeZoneInfo.ConvertTimeToUtc(local, tz); }
catch (ArgumentException) { return TimeZoneInfo.ConvertTimeToUtc(local.AddHours(1), tz); } // ora che non esiste (cambio d'ora)
}
private static string Clean(string html) => Spaces.Replace(WebUtility.HtmlDecode(Tags.Replace(html, " ")), " ").Trim();
}