Aggiunto HtmlCacheService per caching e rate limiting
Introdotto un servizio centralizzato (`HtmlCacheService`) per gestire richieste HTTP con: - Cache HTML (5 minuti) per ridurre richieste duplicate. - Rate limiting (max 5 richieste/sec) e concorrenza limitata (3 richieste parallele). - Retry automatico (max 2 tentativi) e timeout configurabile (15s). - Logging dettagliato per cache hit, retry e richieste fallite. Aggiornati i metodi di caricamento dei nomi e delle informazioni prodotto per utilizzare il nuovo servizio, migliorando caching, gestione degli errori e decodifica delle entità HTML. Aggiunto supporto per il recupero automatico dei nomi generici delle aste e un timer per la pulizia periodica della cache. Documentato il servizio in `FEATURE_HTML_CACHE_SERVICE.md`. Correzioni minori e miglioramenti alla leggibilità del codice.
This commit is contained in:
@@ -1,10 +1,11 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using AutoBidder.Models;
|
||||
using AutoBidder.ViewModels;
|
||||
using AutoBidder.Utilities;
|
||||
using AutoBidder.Services; // ✅ AGGIUNTO per RequestPriority e HtmlResponse
|
||||
|
||||
namespace AutoBidder
|
||||
{
|
||||
@@ -24,13 +25,13 @@ namespace AutoBidder
|
||||
}
|
||||
|
||||
string auctionId;
|
||||
string? productName;
|
||||
string? productName = null;
|
||||
string originalUrl;
|
||||
|
||||
// Verifica se è un URL o solo un ID
|
||||
// Verifica se è un URL o solo un ID
|
||||
if (input.Contains("bidoo.com") || input.Contains("http"))
|
||||
{
|
||||
// È un URL - estrai ID e nome prodotto
|
||||
// È un URL - estrai ID e nome prodotto dall'URL stesso
|
||||
originalUrl = input.Trim();
|
||||
auctionId = ExtractAuctionId(originalUrl);
|
||||
if (string.IsNullOrEmpty(auctionId))
|
||||
@@ -39,32 +40,31 @@ namespace AutoBidder
|
||||
return;
|
||||
}
|
||||
|
||||
productName = ExtractProductName(originalUrl) ?? string.Empty;
|
||||
productName = ExtractProductName(originalUrl);
|
||||
}
|
||||
else
|
||||
{
|
||||
// È solo un ID numerico - costruisci URL generico
|
||||
// È solo un ID numerico - costruisci URL generico
|
||||
auctionId = input.Trim();
|
||||
productName = string.Empty;
|
||||
originalUrl = $"https://it.bidoo.com/auction.php?a=asta_{auctionId}";
|
||||
}
|
||||
|
||||
// Verifica duplicati
|
||||
if (_auctionViewModels.Any(a => a.AuctionId == auctionId))
|
||||
{
|
||||
MessageBox.Show("Asta già monitorata!", "Duplicato", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
MessageBox.Show("Asta già monitorata!", "Duplicato", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
// Crea nome visualizzazione
|
||||
// ✅ MODIFICATO: Nome senza ID (già nella colonna separata)
|
||||
var displayName = string.IsNullOrEmpty(productName)
|
||||
? $"Asta {auctionId}"
|
||||
: $"{System.Net.WebUtility.HtmlDecode(productName)} ({auctionId})";
|
||||
: DecodeAllHtmlEntities(productName);
|
||||
|
||||
// CARICA IMPOSTAZIONI PREDEFINITE SALVATE
|
||||
var settings = Utilities.SettingsManager.Load();
|
||||
|
||||
// ? NUOVO: Determina stato iniziale dalla configurazione
|
||||
// ✅ Determina stato iniziale dalla configurazione
|
||||
bool isActive = false;
|
||||
bool isPaused = false;
|
||||
|
||||
@@ -89,7 +89,7 @@ namespace AutoBidder
|
||||
var auction = new AuctionInfo
|
||||
{
|
||||
AuctionId = auctionId,
|
||||
Name = System.Net.WebUtility.HtmlDecode(displayName),
|
||||
Name = DecodeAllHtmlEntities(displayName),
|
||||
OriginalUrl = originalUrl,
|
||||
BidBeforeDeadlineMs = settings.DefaultBidBeforeDeadlineMs,
|
||||
CheckAuctionOpenBeforeBid = settings.DefaultCheckAuctionOpenBeforeBid,
|
||||
@@ -109,7 +109,7 @@ namespace AutoBidder
|
||||
};
|
||||
_auctionViewModels.Add(vm);
|
||||
|
||||
// ? NUOVO: Auto-start del monitoraggio se l'asta è attiva e il monitoraggio è fermo
|
||||
// ✅ Auto-start del monitoraggio se l'asta è attiva e il monitoraggio è fermo
|
||||
if (isActive && !_isAutomationActive)
|
||||
{
|
||||
_auctionMonitor.Start();
|
||||
@@ -123,6 +123,12 @@ namespace AutoBidder
|
||||
|
||||
var stateText = isActive ? (isPaused ? "Paused" : "Active") : "Stopped";
|
||||
Log($"[ADD] Asta aggiunta con stato={stateText}, Anticipo={settings.DefaultBidBeforeDeadlineMs}ms", Utilities.LogLevel.Info);
|
||||
|
||||
// ✅ NUOVO: Se il nome non è stato estratto, recuperalo in background DOPO l'aggiunta
|
||||
if (string.IsNullOrEmpty(productName))
|
||||
{
|
||||
_ = FetchAuctionNameInBackgroundAsync(auction, vm);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -131,6 +137,85 @@ namespace AutoBidder
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recupera il nome dell'asta in background e aggiorna l'UI quando completa
|
||||
/// </summary>
|
||||
private async Task FetchAuctionNameInBackgroundAsync(AuctionInfo auction, AuctionViewModel vm)
|
||||
{
|
||||
try
|
||||
{
|
||||
// ✅ USA IL SERVIZIO CENTRALIZZATO invece di HttpClient diretto
|
||||
var response = await _htmlCacheService.GetHtmlAsync(
|
||||
auction.OriginalUrl,
|
||||
RequestPriority.Normal,
|
||||
bypassCache: false // Usa cache se disponibile
|
||||
);
|
||||
|
||||
if (!response.Success)
|
||||
{
|
||||
Log($"[WARN] Impossibile recuperare nome per asta {auction.AuctionId}: {response.Error}", LogLevel.Warn);
|
||||
return;
|
||||
}
|
||||
|
||||
// Estrai nome dal <title>
|
||||
var match = System.Text.RegularExpressions.Regex.Match(response.Html, @"<title>([^<]+)</title>");
|
||||
|
||||
if (match.Success)
|
||||
{
|
||||
var productName = match.Groups[1].Value.Trim().Replace(" - Bidoo", "");
|
||||
// ✅ Decodifica entity HTML (incluse quelle non standard)
|
||||
productName = DecodeAllHtmlEntities(productName);
|
||||
// ✅ MODIFICATO: Nome senza ID
|
||||
var newName = productName;
|
||||
|
||||
// Aggiorna il nome su thread UI
|
||||
Dispatcher.Invoke(() =>
|
||||
{
|
||||
auction.Name = newName;
|
||||
// Forza refresh della griglia per mostrare il nuovo nome
|
||||
var tempSource = MultiAuctionsGrid.ItemsSource;
|
||||
MultiAuctionsGrid.ItemsSource = null;
|
||||
MultiAuctionsGrid.ItemsSource = tempSource;
|
||||
SaveAuctions(); // Salva il nome aggiornato
|
||||
Log($"[NAME] Nome recuperato per asta {auction.AuctionId}: {productName}{(response.FromCache ? " (cached)" : "")}", LogLevel.Info);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
Log($"[WARN] Nome non trovato nell'HTML per asta {auction.AuctionId}", LogLevel.Warn);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"[WARN] Errore recupero nome per asta {auction.AuctionId}: {ex.Message}", LogLevel.Warn);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decodifica tutte le entity HTML, incluse quelle non standard come +
|
||||
/// </summary>
|
||||
private string DecodeAllHtmlEntities(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
return text;
|
||||
|
||||
// Prima decodifica entity standard
|
||||
var decoded = System.Net.WebUtility.HtmlDecode(text);
|
||||
|
||||
// ✅ Poi sostituisci entity non standard che WebUtility.HtmlDecode non gestisce
|
||||
decoded = decoded.Replace("+", "+");
|
||||
decoded = decoded.Replace("=", "=");
|
||||
decoded = decoded.Replace("−", "-");
|
||||
decoded = decoded.Replace("×", "×");
|
||||
decoded = decoded.Replace("÷", "÷");
|
||||
decoded = decoded.Replace("%", "%");
|
||||
decoded = decoded.Replace("$", "$");
|
||||
decoded = decoded.Replace("€", "€");
|
||||
decoded = decoded.Replace("£", "£");
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
private async Task AddAuctionFromUrl(string url)
|
||||
{
|
||||
try
|
||||
@@ -151,7 +236,7 @@ namespace AutoBidder
|
||||
// Verifica duplicati
|
||||
if (_auctionViewModels.Any(a => a.AuctionId == auctionId))
|
||||
{
|
||||
MessageBox.Show("Asta già monitorata!", "Duplicato", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
MessageBox.Show("Asta già monitorata!", "Duplicato", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -159,12 +244,16 @@ namespace AutoBidder
|
||||
var name = $"Asta {auctionId}";
|
||||
try
|
||||
{
|
||||
using var httpClient = new System.Net.Http.HttpClient();
|
||||
var html = await httpClient.GetStringAsync(url);
|
||||
var match2 = System.Text.RegularExpressions.Regex.Match(html, @"<title>([^<]+)</title>");
|
||||
if (match2.Success)
|
||||
// ✅ USA IL SERVIZIO CENTRALIZZATO
|
||||
var response = await _htmlCacheService.GetHtmlAsync(url, RequestPriority.Normal);
|
||||
|
||||
if (response.Success)
|
||||
{
|
||||
name = System.Net.WebUtility.HtmlDecode(match2.Groups[1].Value.Trim().Replace(" - Bidoo", ""));
|
||||
var match2 = System.Text.RegularExpressions.Regex.Match(response.Html, @"<title>([^<]+)</title>");
|
||||
if (match2.Success)
|
||||
{
|
||||
name = DecodeAllHtmlEntities(match2.Groups[1].Value.Trim().Replace(" - Bidoo", ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
@@ -172,7 +261,7 @@ namespace AutoBidder
|
||||
// CARICA IMPOSTAZIONI PREDEFINITE SALVATE
|
||||
var settings = Utilities.SettingsManager.Load();
|
||||
|
||||
// ? NUOVO: Determina stato iniziale dalla configurazione
|
||||
// ✅ Determina stato iniziale dalla configurazione
|
||||
bool isActive = false;
|
||||
bool isPaused = false;
|
||||
|
||||
@@ -197,7 +286,7 @@ namespace AutoBidder
|
||||
var auction = new AuctionInfo
|
||||
{
|
||||
AuctionId = auctionId,
|
||||
Name = System.Net.WebUtility.HtmlDecode(name),
|
||||
Name = DecodeAllHtmlEntities(name),
|
||||
OriginalUrl = url,
|
||||
BidBeforeDeadlineMs = settings.DefaultBidBeforeDeadlineMs,
|
||||
CheckAuctionOpenBeforeBid = settings.DefaultCheckAuctionOpenBeforeBid,
|
||||
@@ -217,7 +306,7 @@ namespace AutoBidder
|
||||
};
|
||||
_auctionViewModels.Add(vm);
|
||||
|
||||
// ? NUOVO: Auto-start del monitoraggio se l'asta è attiva e il monitoraggio è fermo
|
||||
// ✅ Auto-start del monitoraggio se l'asta è attiva e il monitoraggio è fermo
|
||||
if (isActive && !_isAutomationActive)
|
||||
{
|
||||
_auctionMonitor.Start();
|
||||
@@ -239,6 +328,57 @@ namespace AutoBidder
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Aggiorna manualmente il nome di un'asta recuperandolo dall'HTML
|
||||
/// </summary>
|
||||
public async Task RefreshAuctionNameAsync(AuctionViewModel vm)
|
||||
{
|
||||
if (vm == null) return;
|
||||
|
||||
try
|
||||
{
|
||||
Log($"[NAME REFRESH] Aggiornamento nome per: {vm.Name}", LogLevel.Info);
|
||||
await FetchAuctionNameInBackgroundAsync(vm.AuctionInfo, vm);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"[ERRORE] Refresh nome asta: {ex.Message}", LogLevel.Error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Controlla se ci sono aste con nomi generici e prova a recuperarli dopo un delay
|
||||
/// </summary>
|
||||
private async Task RetryFailedAuctionNamesAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Aspetta 30 secondi prima di ritentare (dà tempo alle altre richieste di completare)
|
||||
await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(30));
|
||||
|
||||
// Trova aste con nomi generici "Asta XXXX"
|
||||
var auctionsWithGenericNames = _auctionViewModels
|
||||
.Where(vm => vm.Name.StartsWith("Asta ") && !vm.Name.Contains("Shop") && !vm.Name.Contains("€"))
|
||||
.ToList();
|
||||
|
||||
if (auctionsWithGenericNames.Count > 0)
|
||||
{
|
||||
Log($"[NAME RETRY] Trovate {auctionsWithGenericNames.Count} aste con nomi generici. Ritento recupero...", LogLevel.Info);
|
||||
|
||||
// Ritenta il recupero per ognuna (con delay tra una e l'altra per non sovraccaricare)
|
||||
foreach (var vm in auctionsWithGenericNames)
|
||||
{
|
||||
await FetchAuctionNameInBackgroundAsync(vm.AuctionInfo, vm);
|
||||
await System.Threading.Tasks.Task.Delay(2000); // 2 secondi tra una richiesta e l'altra
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"[WARN] Errore retry nomi aste: {ex.Message}", LogLevel.Warn);
|
||||
}
|
||||
}
|
||||
|
||||
private void SaveAuctions()
|
||||
{
|
||||
try
|
||||
@@ -256,7 +396,7 @@ namespace AutoBidder
|
||||
{
|
||||
try
|
||||
{
|
||||
// ? Carica impostazioni
|
||||
// ✅ Carica impostazioni
|
||||
var settings = Utilities.SettingsManager.Load();
|
||||
|
||||
// Ottieni username corrente dalla sessione per ripristinare IsMyBid
|
||||
@@ -269,10 +409,10 @@ namespace AutoBidder
|
||||
// Protezione: rimuovi eventuali BidHistory null
|
||||
auction.BidHistory = auction.BidHistory?.Where(b => b != null).ToList() ?? new System.Collections.Generic.List<BidHistory>();
|
||||
|
||||
// Decode HTML entities
|
||||
try { auction.Name = System.Net.WebUtility.HtmlDecode(auction.Name ?? string.Empty); } catch { }
|
||||
// ✅ Decode HTML entities (incluse quelle non standard)
|
||||
try { auction.Name = DecodeAllHtmlEntities(auction.Name ?? string.Empty); } catch { }
|
||||
|
||||
// ? Ripristina IsMyBid per tutte le puntate in RecentBids
|
||||
// ✅ Ripristina IsMyBid per tutte le puntate in RecentBids
|
||||
if (auction.RecentBids != null && auction.RecentBids.Count > 0 && !string.IsNullOrEmpty(currentUsername))
|
||||
{
|
||||
foreach (var bid in auction.RecentBids)
|
||||
@@ -281,11 +421,12 @@ namespace AutoBidder
|
||||
}
|
||||
}
|
||||
|
||||
// ? NUOVO: Gestione stato in base a RememberAuctionStates
|
||||
|
||||
// ✅ NUOVO: Gestione stato in base a RememberAuctionStates
|
||||
if (settings.RememberAuctionStates)
|
||||
{
|
||||
// MODO 1: Ripristina lo stato salvato di ogni asta (IsActive e IsPaused vengono dal file salvato)
|
||||
// Non serve fare nulla, lo stato è già quello salvato nel file
|
||||
// Non serve fare nulla, lo stato è già quello salvato nel file
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -314,7 +455,7 @@ namespace AutoBidder
|
||||
_auctionViewModels.Add(vm);
|
||||
}
|
||||
|
||||
// ? Avvia monitoraggio se ci sono aste in stato Active O Paused
|
||||
// ✅ Avvia monitoraggio se ci sono aste in stato Active O Paused
|
||||
bool hasActiveOrPausedAuctions = auctions.Any(a => a.IsActive);
|
||||
|
||||
if (hasActiveOrPausedAuctions && auctions.Count > 0)
|
||||
@@ -397,7 +538,7 @@ namespace AutoBidder
|
||||
// Aggiorna Valore (Compra Subito)
|
||||
if (auction.BuyNowPrice.HasValue)
|
||||
{
|
||||
AuctionMonitor.ProductBuyNowPriceText.Text = $"{auction.BuyNowPrice.Value:F2}€";
|
||||
AuctionMonitor.ProductBuyNowPriceText.Text = $"{auction.BuyNowPrice.Value:F2}€";
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -407,7 +548,7 @@ namespace AutoBidder
|
||||
// Aggiorna Spese di Spedizione
|
||||
if (auction.ShippingCost.HasValue)
|
||||
{
|
||||
AuctionMonitor.ProductShippingCostText.Text = $"{auction.ShippingCost.Value:F2}€";
|
||||
AuctionMonitor.ProductShippingCostText.Text = $"{auction.ShippingCost.Value:F2}€";
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -430,38 +571,81 @@ namespace AutoBidder
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Carica le informazioni del prodotto in background quando selezioni un'asta
|
||||
/// Carica le informazioni del prodotto (e nome se generico) in background quando selezioni un'asta
|
||||
/// </summary>
|
||||
private async System.Threading.Tasks.Task LoadProductInfoInBackgroundAsync(AuctionInfo auction)
|
||||
{
|
||||
try
|
||||
{
|
||||
Log($"[PRODUCT INFO] Caricamento automatico per: {auction.Name}", Utilities.LogLevel.Info);
|
||||
bool hasGenericName = auction.Name.StartsWith("Asta ") &&
|
||||
!auction.Name.Contains("Shop") &&
|
||||
!auction.Name.Contains("€") &&
|
||||
!auction.Name.Contains("Buono") &&
|
||||
!auction.Name.Contains("Carburante");
|
||||
|
||||
// Scarica HTML
|
||||
using var httpClient = new System.Net.Http.HttpClient();
|
||||
httpClient.Timeout = TimeSpan.FromSeconds(10);
|
||||
Log($"[PRODUCT INFO] Caricamento automatico per: {auction.Name}{(hasGenericName ? " (+ nome generico)" : "")}", Utilities.LogLevel.Info);
|
||||
|
||||
var html = await httpClient.GetStringAsync(auction.OriginalUrl);
|
||||
// ✅ USA IL SERVIZIO CENTRALIZZATO
|
||||
var response = await _htmlCacheService.GetHtmlAsync(
|
||||
auction.OriginalUrl,
|
||||
RequestPriority.High, // Priorità alta per info prodotto
|
||||
bypassCache: false
|
||||
);
|
||||
|
||||
// Estrai informazioni prodotto
|
||||
var extracted = Utilities.ProductValueCalculator.ExtractProductInfo(html, auction);
|
||||
if (!response.Success)
|
||||
{
|
||||
Log($"[PRODUCT INFO] Errore caricamento: {response.Error}", Utilities.LogLevel.Warn);
|
||||
return;
|
||||
}
|
||||
|
||||
bool updated = false;
|
||||
|
||||
// 1. ✅ Se nome generico, estrai nome reale dal <title>
|
||||
if (hasGenericName)
|
||||
{
|
||||
var matchTitle = System.Text.RegularExpressions.Regex.Match(response.Html, @"<title>([^<]+)</title>");
|
||||
if (matchTitle.Success)
|
||||
{
|
||||
var productName = matchTitle.Groups[1].Value.Trim().Replace(" - Bidoo", "");
|
||||
productName = DecodeAllHtmlEntities(productName);
|
||||
// ✅ MODIFICATO: Nome senza ID
|
||||
var newName = productName;
|
||||
|
||||
auction.Name = newName;
|
||||
updated = true;
|
||||
Log($"[NAME] Nome recuperato: {productName}{(response.FromCache ? " (cached)" : "")}", LogLevel.Info);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. ✅ Estrai informazioni prodotto (prezzo, spedizione, limiti)
|
||||
var extracted = Utilities.ProductValueCalculator.ExtractProductInfo(response.Html, auction);
|
||||
if (extracted)
|
||||
{
|
||||
// Salva le aste con le nuove informazioni
|
||||
updated = true;
|
||||
Log($"[PRODUCT INFO] Valore={auction.BuyNowPrice:F2}€, Spedizione={auction.ShippingCost:F2}€{(response.FromCache ? " (cached)" : "")}", Utilities.LogLevel.Success);
|
||||
}
|
||||
|
||||
// 3. ✅ Salva e aggiorna UI solo se qualcosa è cambiato
|
||||
if (updated)
|
||||
{
|
||||
SaveAuctions();
|
||||
|
||||
// Aggiorna UI sul thread UI
|
||||
Dispatcher.Invoke(() =>
|
||||
{
|
||||
// Refresh griglia per mostrare nome aggiornato
|
||||
if (hasGenericName)
|
||||
{
|
||||
var tempSource = MultiAuctionsGrid.ItemsSource;
|
||||
MultiAuctionsGrid.ItemsSource = null;
|
||||
MultiAuctionsGrid.ItemsSource = tempSource;
|
||||
}
|
||||
|
||||
// Refresh dettagli se ancora selezionata
|
||||
if (_selectedAuction != null && _selectedAuction.AuctionId == auction.AuctionId)
|
||||
{
|
||||
UpdateSelectedAuctionDetails(_selectedAuction);
|
||||
}
|
||||
});
|
||||
|
||||
Log($"[PRODUCT INFO] Valore={auction.BuyNowPrice:F2}€, Spedizione={auction.ShippingCost:F2}€", Utilities.LogLevel.Success);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
Reference in New Issue
Block a user