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>
486 lines
24 KiB
C#
486 lines
24 KiB
C#
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,
|
|
DateTime? LastRewardsUtc = null, string? RewardsSummary = null);
|
|
|
|
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, _lastRewardsUtc;
|
|
private string? _lastSummary, _rewardsSummary;
|
|
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, _lastRewardsUtc, _rewardsSummary);
|
|
}
|
|
|
|
/// <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);
|
|
|
|
/// <summary>La lettura delle ricompense, a intervalli di ore, se accesa e con l'utente collegato.</summary>
|
|
public Task RunRewardsAsync(CancellationToken ct) => Task.Run(async () =>
|
|
{
|
|
if (!await DelayAsync(TimeSpan.FromMinutes(3), ct).ConfigureAwait(false)) return;
|
|
while (!ct.IsCancellationRequested)
|
|
{
|
|
var s = _settings();
|
|
if (s.FreeBidsRewardsHours > 0 && _canRedeem())
|
|
{
|
|
try { await SyncRewardsAsync(ct).ConfigureAwait(false); }
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
|
|
catch (Exception ex) { Note($"lettura delle ricompense non riuscita: {ex.Message}", warn: true); }
|
|
}
|
|
var hours = Math.Max(1, s.FreeBidsRewardsHours);
|
|
if (!await DelayAsync(TimeSpan.FromHours(hours) + TimeSpan.FromSeconds(_rng.Next(0, 301)), ct).ConfigureAwait(false)) return;
|
|
}
|
|
}, ct);
|
|
|
|
/// <summary>
|
|
/// Legge le ricompense ottenute (forzieri) e la prima pagina della cronologia crediti, salva le nuove in
|
|
/// <c>account_rewards</c> e confronta quelle di oggi da collegamento con i riscatti riusciti del bot.
|
|
/// </summary>
|
|
public async Task<string> SyncRewardsAsync(CancellationToken ct)
|
|
{
|
|
if (!_canRedeem()) return "nessuna lettura: serve l'utente di Bidoo collegato";
|
|
var fb = _refs().FreeBids;
|
|
var all = new List<AccountReward>();
|
|
var problems = new List<string>();
|
|
|
|
var (chestPage, chestError) = await _api.GetAccountPageAsync(fb.RewardsPage, ct).ConfigureAwait(false);
|
|
var chests = chestPage != null ? RewardsPages.ParseChests(chestPage, AppInfo.TimeZone) : new RewardsRead([], chestError);
|
|
if (chests.Error != null) problems.Add($"ricompense: {chests.Error}");
|
|
all.AddRange(chests.Items);
|
|
|
|
await Task.Delay(1000 + _rng.Next(0, 2000), ct).ConfigureAwait(false);
|
|
var (creditPage, creditError) = await _api.GetAccountPageAsync(fb.CreditsHistoryPage, ct).ConfigureAwait(false);
|
|
var credits = creditPage != null ? RewardsPages.ParseCreditHistory(creditPage) : new RewardsRead([], creditError);
|
|
if (credits.Error != null) problems.Add($"cronologia crediti: {credits.Error}");
|
|
all.AddRange(credits.Items);
|
|
|
|
var keys = all.Select(r => r.Key).Distinct(StringComparer.Ordinal).ToArray();
|
|
var known = keys.Length == 0 ? new HashSet<string>(StringComparer.Ordinal)
|
|
: (await _db.QueryAsync("SELECT key FROM account_rewards WHERE key = ANY($1)", r => r.Str("key"), keys).ConfigureAwait(false))
|
|
.ToHashSet(StringComparer.Ordinal);
|
|
var fresh = all.Where(r => known.Add(r.Key)).ToList();
|
|
foreach (var r in fresh)
|
|
_queue.Enqueue("INSERT INTO account_rewards(key, kind, ts, bids, free, source, description) VALUES($1, $2, $3, $4, $5, $6, $7) " +
|
|
"ON CONFLICT (key) DO NOTHING", r.Key, r.Kind, r.AtUtc, r.Bids, r.Free, r.Source, LogText.Clean(r.Description));
|
|
|
|
var today = DateOnly.FromDateTime(AppInfo.LocalNow);
|
|
var (redeemed, gained) = await CreditedTodayWithGainAsync(ct).ConfigureAwait(false);
|
|
var head = $"ricompense lette: {chests.Items.Count} forzieri e {credits.Items.Count} movimenti, {fresh.Count} nuovi";
|
|
var text = chests.Error == null ? $"{head}; {RewardsPages.CompareToday(chests.Items, today, AppInfo.TimeZone, redeemed, gained)}" : head;
|
|
foreach (var p in problems) Note(p, warn: true);
|
|
_rewardsSummary = text;
|
|
_lastRewardsUtc = DateTime.UtcNow;
|
|
Note(text);
|
|
return text;
|
|
}
|
|
|
|
public static bool InHours(AppSettings s, int hour) =>
|
|
s.FreeBidsHoursStart == s.FreeBidsHoursEnd
|
|
|| (s.FreeBidsHoursStart < s.FreeBidsHoursEnd
|
|
? 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++;
|
|
}
|
|
}
|
|
|
|
// Seconda fonte: la campanella di Bidoo, letta senza segnare nulla.
|
|
if (_settings().FreeBidsUseNotifications)
|
|
{
|
|
var (body, error) = await _api.GetNotificationsAsync(ct).ConfigureAwait(false);
|
|
var bell = body != null ? RewardsPages.ParseNotifications(body) : new NotificationLinks(0, [], error);
|
|
if (bell.Error != null) Note($"campanella: {bell.Error}");
|
|
foreach (var (_, href) in bell.Links)
|
|
{
|
|
var v = PromoLinkCheck.Check(href, refs.Host, fb.PromoPaths, fb.PromoExtraParameters);
|
|
if (v.Ok) candidates.Add(new RedeemCandidate(v.Link!, "campanella", 0, false, 0));
|
|
else rejected++;
|
|
}
|
|
}
|
|
|
|
var known = await KnownAsync(candidates.Select(c => c.Link.Code).Distinct().ToArray(), ct).ConfigureAwait(false);
|
|
var s = _settings();
|
|
var plan = RedeemPlanner.Choose(candidates, known, new RedeemLimits(s.FreeBidsMaxPerRun, s.FreeBidsMaxPerDay, s.FreeBidsMaxAttempts),
|
|
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 Count, int Gained)> CreditedTodayWithGainAsync(CancellationToken ct)
|
|
{
|
|
ct.ThrowIfCancellationRequested();
|
|
var midnight = TimeZoneInfo.ConvertTimeToUtc(AppInfo.LocalNow.Date, AppInfo.TimeZone);
|
|
var rows = await _db.QueryAsync(
|
|
"SELECT count(*)::int AS n, coalesce(sum(gained) FILTER (WHERE gained > 0), 0)::int AS g FROM promo_redemptions " +
|
|
"WHERE ts >= $1 AND outcome = ANY($2)",
|
|
r => (r.Int("n"), r.Int("g")), midnight,
|
|
new[] { OutcomeCode(RedeemOutcome.Credited), OutcomeCode(RedeemOutcome.CreditedWithWarning) }).ConfigureAwait(false);
|
|
return rows.Count > 0 ? rows[0] : (0, 0);
|
|
}
|
|
|
|
private async Task<int> CreditedTodayAsync(CancellationToken ct)
|
|
{
|
|
ct.ThrowIfCancellationRequested();
|
|
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();
|
|
}
|
|
}
|