Files
Mimante/Mimante/Core/MainWindow.UserInfo.cs
T
Alby96 7ca504a70a Add utility classes for theme management, waiting, watched products, and notifications
- Implement ThemeManager for dynamic light/dark theme switching in the application.
- Create Wait class for cancellable delays without exceptions for smoother user experience.
- Introduce WatchedProductsStore to manage and persist watched products in JSON format.
- Add WindowsNotifier for system notifications to inform users of important events.
- Develop ProductViewModel to encapsulate product data and manage UI interactions effectively.
2026-08-04 21:49:53 +02:00

423 lines
18 KiB
C#

using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using AutoBidder.Services;
using AutoBidder.Utilities;
namespace AutoBidder
{
/// <summary>
/// User info and banner management - REFACTORED con SessionService
/// </summary>
public partial class MainWindow
{
// Creati in InitializeUserInfo(), non nel costruttore.
private System.Windows.Threading.DispatcherTimer? _userBannerTimer;
private System.Windows.Threading.DispatcherTimer? _userHtmlTimer;
private System.Windows.Threading.DispatcherTimer? _toConfirmTimer;
private SessionService _sessionService = null!;
/// <summary>
/// Aste vinte in attesa di conferma su Bidoo, o <c>-1</c> finché non è arrivata una
/// risposta utilizzabile. È un <c>int</c> e non un <c>int?</c> perché lo scrive la
/// rete e lo legge il battito dell'interfaccia: un annullabile sono due campi, e
/// due campi si possono leggere a metà aggiornamento.
/// </summary>
private int _auctionsToConfirmRaw = Unknown;
private const int Unknown = -1;
/// <summary>Aste da confermare, o <c>null</c> se ancora non si sa.</summary>
private int? AuctionsToConfirm
{
get
{
var value = System.Threading.Volatile.Read(ref _auctionsToConfirmRaw);
return value < 0 ? null : value;
}
}
private void InitializeUserInfoTimers()
{
// Timer per aggiornamento dati utente da HTML ogni 5 minuti (PRINCIPALE)
_userHtmlTimer = new System.Windows.Threading.DispatcherTimer();
_userHtmlTimer.Interval = TimeSpan.FromMinutes(5);
_userHtmlTimer.Tick += UserHtmlTimer_Tick;
_userHtmlTimer.Start();
// Timer per aggiornamento banner API ogni 10 minuti (SECONDARIO - fallback)
_userBannerTimer = new System.Windows.Threading.DispatcherTimer();
_userBannerTimer.Interval = TimeSpan.FromMinutes(10);
_userBannerTimer.Tick += UserBannerTimer_Tick;
_userBannerTimer.Start();
// Aste da confermare: una richiesta da un byte, quindi si può chiedere spesso.
// Un minuto è il compromesso fra "il numero compare subito dopo una vincita"
// e "non si tempesta il server per un dato che cambia di rado".
_toConfirmTimer = new System.Windows.Threading.DispatcherTimer();
_toConfirmTimer.Interval = TimeSpan.FromSeconds(60);
_toConfirmTimer.Tick += (_, _) => _ = RefreshAuctionsToConfirmAsync();
_toConfirmTimer.Start();
}
/// <summary>
/// Rilegge da Bidoo quante aste vinte aspettano conferma.
///
/// <para>Una risposta non utilizzabile <b>non</b> azzera il valore noto: se la rete
/// cade, la barra continua a mostrare l'ultimo numero certo invece di far sparire
/// una vincita che esiste.</para>
/// </summary>
private async Task RefreshAuctionsToConfirmAsync()
{
try
{
var session = _auctionMonitor.GetSession();
if (session == null || string.IsNullOrEmpty(session.Username))
{
System.Threading.Volatile.Write(ref _auctionsToConfirmRaw, Unknown);
return;
}
var count = await _auctionMonitor.GetAuctionsWonToConfirmAsync().ConfigureAwait(false);
if (count.HasValue) System.Threading.Volatile.Write(ref _auctionsToConfirmRaw, count.Value);
}
catch { /* la barra non deve mai disturbare il resto */ }
}
private void InitializeSessionService()
{
// NUOVO: Inizializza SessionService
_sessionService = new SessionService(_auctionMonitor.GetApiClient());
// Event handlers
_sessionService.OnLog += (msg) => Log(msg, LogLevel.Info);
_sessionService.OnSessionChanged += (session) =>
{
Dispatcher.Invoke(() => SetUserBanner(session.Username, session.RemainingBids));
};
// La sessione salvata va ripresa, altrimenti salvarla non serve a niente.
_ = RestoreSavedSessionAsync();
}
/// <summary>
/// Riprende la sessione salvata su disco e la riattiva verso Bidoo.
///
/// Senza questo passaggio il cookie veniva scritto in session.dat e mai più letto:
/// a ogni avvio l'applicazione risultava "Non connesso" e bisognava reincollarlo,
/// pur avendone una copia valida sul disco.
///
/// Non blocca l'avvio: la validazione richiede un giro di rete, quindi la finestra
/// si apre subito e il banner si aggiorna quando la risposta arriva.
/// </summary>
private async Task RestoreSavedSessionAsync()
{
try
{
var saved = _sessionService.LoadSession();
if (saved == null || string.IsNullOrWhiteSpace(saved.CookieString)) return;
Log("[SESSION] Sessione salvata trovata: verifica in corso…", LogLevel.Info);
// Il cookie potrebbe essere scaduto da giorni: si riattiva contro il server
// invece di fidarsi del file.
var result = await _sessionService.ValidateAndActivateSessionAsync(
saved.CookieString, saved.Username);
if (result.Success && result.Session != null)
{
// Il motore deve conoscere il cookie per poter interrogare e puntare.
_auctionMonitor.InitializeSessionWithCookie(
saved.CookieString, result.Session.Username);
Dispatcher.Invoke(() =>
{
SetUserBanner(result.Session.Username, result.Session.RemainingBids);
RefreshSettingsSessionStatus();
});
Log($"[SESSION] Riconnesso come {result.Session.Username}", LogLevel.Success);
}
else
{
// Si lascia il cookie sul disco: l'utente lo vede in Impostazioni e
// decide se rinnovarlo dal browser.
Log($"[SESSION] Sessione salvata non più valida: {result.ErrorMessage}", LogLevel.Warning);
}
}
catch (Exception ex)
{
Log($"[SESSION] Ripristino non riuscito: {ex.Message}", LogLevel.Error);
}
}
private void SetUserBanner(string username, int? remainingBids)
{
try
{
var session = _sessionService?.GetCurrentSession();
if (!string.IsNullOrEmpty(username))
{
// === CONNESSO ===
// Puntate, credito e aste da confermare li ridisegna il battito da un
// secondo (RefreshAccountPills) leggendo la sessione viva: scriverli
// anche qui non aggiungerebbe nulla e riporterebbe il rischio di due
// fonti che si contraddicono.
AuctionMonitor.UpdateAccountStatus(
remainingBids ?? session?.RemainingBids,
session is null ? null : (decimal)session.ShopCredit,
AuctionsToConfirm);
// Appena la sessione è viva si può finalmente chiedere quante vincite
// aspettano conferma: prima non si poteva sapere.
_ = RefreshAuctionsToConfirmAsync();
// === SIDEBAR - Mostra dati utente ===
SidebarUsernameText.Text = username;
SidebarUsernameText.Foreground = new System.Windows.Media.SolidColorBrush(
System.Windows.Media.Color.FromRgb(0, 216, 0)); // Verde
SidebarUsernameText.FontWeight = System.Windows.FontWeights.Bold;
SidebarUsernameText.ToolTip = $"Connesso come {username} - Click per disconnettere";
// Solo l'ID: l'indirizzo di posta non aggiungeva nulla di utile qui.
if (session?.UserId > 0)
{
SidebarUserIdText.Text = $"ID: {session.UserId}";
SidebarUserIdText.Visibility = System.Windows.Visibility.Visible;
}
else
{
SidebarUserIdText.Visibility = System.Windows.Visibility.Collapsed;
}
SidebarUserDetailsPanel.Visibility = System.Windows.Visibility.Visible;
}
else
{
// === NON CONNESSO ===
// Senza sessione questi numeri non esistono: un trattino lo dice,
// uno zero mentirebbe.
System.Threading.Volatile.Write(ref _auctionsToConfirmRaw, Unknown);
AuctionMonitor.UpdateAccountStatus(null, null, null);
// Nascondi indicatore limite
MinBidsLimitIndicator.Visibility = Visibility.Collapsed;
// === SIDEBAR - Mostra "Non connesso" ===
SidebarUsernameText.Text = "Non connesso";
SidebarUsernameText.Foreground = new System.Windows.Media.SolidColorBrush(
System.Windows.Media.Color.FromRgb(255, 82, 82)); // Rosso chiaro (#FF5252)
SidebarUsernameText.FontWeight = System.Windows.FontWeights.Bold;
SidebarUsernameText.ToolTip = "Non connesso - Click per accedere tramite browser";
// Nascondi dettagli (ID + Email)
SidebarUserDetailsPanel.Visibility = System.Windows.Visibility.Collapsed;
}
}
catch { }
}
private async void UserBannerTimer_Tick(object? sender, EventArgs e)
{
// Usa SessionService per refresh
if (_sessionService != null)
{
await _sessionService.RefreshUserInfoAsync();
}
}
private async void UserHtmlTimer_Tick(object? sender, EventArgs e)
{
// Usa SessionService per refresh
if (_sessionService != null)
{
await _sessionService.RefreshUserInfoAsync();
}
}
/// <summary>
/// Carica sessione salvata
/// </summary>
private void LoadSavedSession()
{
try
{
var session = _sessionService?.GetCurrentSession();
if (session != null && session.IsValid)
{
StartButton.IsEnabled = true;
Log($"[SESSION] Ripristino sessione per: {session.Username}", LogLevel.Info);
// Aggiorna UI con stato connesso (ottimistico)
SetUserBanner(session.Username, session.RemainingBids);
// Verifica validit cookie in background
System.Threading.Tasks.Task.Run(async () =>
{
try
{
Log("[SESSION] Verifica validit sessione...", LogLevel.Info);
var success = await _auctionMonitor.UpdateUserInfoAsync();
var updatedSession = _auctionMonitor.GetSession();
Dispatcher.Invoke(() =>
{
if (success && updatedSession != null && !string.IsNullOrEmpty(updatedSession.Username))
{
SetUserBanner(updatedSession.Username, updatedSession.RemainingBids);
Log($"[SESSION] Sessione valida - {updatedSession.Username} ({updatedSession.RemainingBids} puntate)", LogLevel.Success);
}
else
{
SetUserBanner(string.Empty, 0);
Log("[SESSION] Sessione scaduta", LogLevel.Warning);
CheckBrowserCookieAfterWebViewReady();
}
});
}
catch (Exception ex)
{
Dispatcher.Invoke(() =>
{
SetUserBanner(string.Empty, 0);
Log($"[SESSION] Errore verifica sessione: {ex.Message}", LogLevel.Warning);
CheckBrowserCookieAfterWebViewReady();
});
}
});
}
else
{
Log("[SESSION] Nessuna sessione salvata", LogLevel.Info);
CheckBrowserCookieAfterWebViewReady();
SetUserBanner(string.Empty, 0);
}
}
catch (Exception ex)
{
Log($"[ERRORE] Caricamento sessione: {ex.Message}", LogLevel.Error);
CheckBrowserCookieAfterWebViewReady();
SetUserBanner(string.Empty, 0);
}
}
/// <summary>
/// Attende che WebView sia pronta, poi verifica presenza cookie
/// </summary>
private void CheckBrowserCookieAfterWebViewReady()
{
System.Threading.Tasks.Task.Run(async () =>
{
try
{
// Aspetta che WebView sia inizializzata (max 60 secondi)
var webViewReady = await WaitForWebViewInitAsync(60);
if (!webViewReady)
{
await Dispatcher.InvokeAsync(() =>
{
Log("[WARN] WebView non inizializzata dopo 60 secondi", LogLevel.Warning);
Log("[INFO] Per accedere:", LogLevel.Info);
Log("[INFO] 1. Click su 'Non connesso' nella sidebar", LogLevel.Info);
Log("[INFO] 2. Si aprir la scheda Browser", LogLevel.Info);
Log("[INFO] 3. Fai login su Bidoo", LogLevel.Info);
Log("[INFO] 4. La connessione sar automatica", LogLevel.Info);
});
return;
}
// WebView pronta - verifica cookie
await Dispatcher.InvokeAsync(async () =>
{
var browserCookie = await GetCookieFromWebView();
if (string.IsNullOrEmpty(browserCookie))
{
Log("[INFO] Nessun cookie nel browser", LogLevel.Info);
Log("[INFO] Per accedere:", LogLevel.Info);
Log("[INFO] 1. Click su 'Non connesso' nella sidebar", LogLevel.Info);
Log("[INFO] 2. Si aprir la scheda Browser", LogLevel.Info);
Log("[INFO] 3. Fai login su Bidoo", LogLevel.Info);
Log("[INFO] 4. La connessione sar automatica", LogLevel.Info);
}
else
{
Log("[INFO] Cookie rilevato nel browser - importazione in corso...", LogLevel.Info);
}
});
}
catch (Exception ex)
{
Log($"[WARN] Errore verifica cookie: {ex.Message}", LogLevel.Warning);
}
});
}
/// <summary>
/// Ridisegna subito la barra del conto dopo una puntata, senza aspettare il battito.
///
/// <para>Prima aggiornava il numero solo se era maggiore di zero: finite le puntate,
/// la barra restava sull'ultimo valore positivo — cioè mentiva proprio nel momento
/// in cui contava di più.</para>
/// </summary>
public void UpdateRemainingBidsDisplay()
{
try
{
RefreshAccountPills();
}
catch (Exception ex)
{
Log($"[ERROR] Errore aggiornamento banner: {ex.Message}", LogLevel.Error);
}
}
/// <summary>
/// Indicatore del limite minimo puntate, accanto al saldo.
///
/// <para>Il colore va ricalcolato anche a zero puntate: era proprio il caso in cui
/// prima restava dell'ultimo colore utile, cioè verde, mentre il conto era vuoto.</para>
/// </summary>
private void UpdateMinBidsIndicator(int minBidsLimit)
{
try
{
if (minBidsLimit <= 0)
{
MinBidsLimitIndicator.Visibility = Visibility.Collapsed;
return;
}
MinBidsLimitIndicator.Visibility = Visibility.Visible;
MinBidsLimitIndicator.Text = $"({minBidsLimit})";
MinBidsLimitIndicator.ToolTip =
$"Limite minimo puntate attivo: il bot non scende sotto {minBidsLimit} puntate";
var session = _auctionMonitor.GetSession();
if (session == null || string.IsNullOrEmpty(session.Username))
{
MinBidsLimitIndicator.SetResourceReference(
System.Windows.Controls.TextBlock.ForegroundProperty, "Brush.TextFaint");
return;
}
var key =
session.RemainingBids <= minBidsLimit ? "Brush.Danger" :
session.RemainingBids <= minBidsLimit + 10 ? "Brush.Warning" :
"Brush.Success";
MinBidsLimitIndicator.SetResourceReference(
System.Windows.Controls.TextBlock.ForegroundProperty, key);
}
catch { }
}
}
}