From 12afcb3d83d1f9519ef8f3d9f94ef1b646b55d1a Mon Sep 17 00:00:00 2001 From: Ricardo Carneiro Date: Mon, 11 Aug 2025 19:20:39 -0300 Subject: [PATCH] fix: adsense --- Controllers/AccountController.cs | 4 ++ Controllers/HomeController.cs | 86 ++++++++++++++++-------------- Controllers/PagamentoController.cs | 7 ++- Controllers/PremiumController.cs | 3 ++ Controllers/QRController.cs | 6 ++- Services/AdDisplayService.cs | 6 +++ Views/Shared/_AdSpace.cshtml | 20 ++++--- Views/Shared/_Layout.cshtml | 61 +++++++++++---------- wwwroot/js/qr-speed-generator.js | 83 ---------------------------- 9 files changed, 113 insertions(+), 163 deletions(-) diff --git a/Controllers/AccountController.cs b/Controllers/AccountController.cs index 51c032c..cbd42ee 100644 --- a/Controllers/AccountController.cs +++ b/Controllers/AccountController.cs @@ -29,6 +29,7 @@ namespace QRRapidoApp.Controllers [HttpGet] public IActionResult Login(string returnUrl = "/") { + _adDisplayService.SetViewBagAds(ViewBag); ViewBag.ReturnUrl = returnUrl; return View(); } @@ -69,6 +70,7 @@ namespace QRRapidoApp.Controllers { try { + _adDisplayService.SetViewBagAds(ViewBag); var result = await HttpContext.AuthenticateAsync(scheme); if (!result.Succeeded) { @@ -154,6 +156,7 @@ namespace QRRapidoApp.Controllers ViewBag.QRHistory = await _userService.GetUserQRHistoryAsync(userId, 10); ViewBag.MonthlyQRCount = await _userService.GetQRCountThisMonthAsync(userId); ViewBag.IsPremium = await _adDisplayService.HasValidPremiumSubscription(userId); + _adDisplayService.SetViewBagAds(ViewBag); return View(user); } @@ -202,6 +205,7 @@ namespace QRRapidoApp.Controllers [Authorize] public async Task History() { + _adDisplayService.SetViewBagAds(ViewBag); var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (string.IsNullOrEmpty(userId)) { diff --git a/Controllers/HomeController.cs b/Controllers/HomeController.cs index 752fbf1..f0288f7 100644 --- a/Controllers/HomeController.cs +++ b/Controllers/HomeController.cs @@ -32,7 +32,8 @@ namespace QRRapidoApp.Controllers ViewBag.IsPremium = await _adDisplayService.HasValidPremiumSubscription(userId ?? ""); ViewBag.IsAuthenticated = User.Identity?.IsAuthenticated ?? false; ViewBag.UserName = User.Identity?.Name ?? ""; - + _adDisplayService.SetViewBagAds(ViewBag); + // SEO and Analytics data ViewBag.Title = _config["App:TaglinePT"]; ViewBag.Keywords = _config["SEO:KeywordsPT"]; @@ -59,7 +60,8 @@ namespace QRRapidoApp.Controllers ViewBag.Title = _localizer["PrivacyPolicyTitle"]; ViewBag.Description = _localizer["PrivacyPolicyDescription"]; - + _adDisplayService.SetViewBagAds(ViewBag); + return View(); } @@ -74,7 +76,8 @@ namespace QRRapidoApp.Controllers ViewBag.Title = _localizer["TermsOfUseTitle"]; ViewBag.Description = _localizer["TermsOfUseDescription"]; - + _adDisplayService.SetViewBagAds(ViewBag); + return View(); } @@ -90,6 +93,7 @@ namespace QRRapidoApp.Controllers { try { + _adDisplayService.SetViewBagAds(ViewBag); // This would lookup the dynamic QR content from cache/database // For now, return a placeholder return Redirect("https://qrrapido.site"); @@ -112,44 +116,44 @@ namespace QRRapidoApp.Controllers public IActionResult Sitemap() { var sitemap = $@" - - - https://qrrapido.site/ - {DateTime.UtcNow:yyyy-MM-dd} - daily - 1.0 - - - https://qrrapido.site/pt/ - {DateTime.UtcNow:yyyy-MM-dd} - daily - 0.9 - - - https://qrrapido.site/es/ - {DateTime.UtcNow:yyyy-MM-dd} - daily - 0.9 - - - https://qrrapido.site/Premium/Upgrade - {DateTime.UtcNow:yyyy-MM-dd} - weekly - 0.8 - - - https://qrrapido.site/privacy - {DateTime.UtcNow:yyyy-MM-dd} - monthly - 0.5 - - - https://qrrapido.site/terms - {DateTime.UtcNow:yyyy-MM-dd} - monthly - 0.5 - -"; + + + https://qrrapido.site/ + {DateTime.UtcNow:yyyy-MM-dd} + daily + 1.0 + + + https://qrrapido.site/pt/ + {DateTime.UtcNow:yyyy-MM-dd} + daily + 0.9 + + + https://qrrapido.site/es/ + {DateTime.UtcNow:yyyy-MM-dd} + daily + 0.9 + + + https://qrrapido.site/Premium/Upgrade + {DateTime.UtcNow:yyyy-MM-dd} + weekly + 0.8 + + + https://qrrapido.site/privacy + {DateTime.UtcNow:yyyy-MM-dd} + monthly + 0.5 + + + https://qrrapido.site/terms + {DateTime.UtcNow:yyyy-MM-dd} + monthly + 0.5 + + "; return Content(sitemap, "application/xml"); } diff --git a/Controllers/PagamentoController.cs b/Controllers/PagamentoController.cs index 81b6ef4..75f74e7 100644 --- a/Controllers/PagamentoController.cs +++ b/Controllers/PagamentoController.cs @@ -13,16 +13,18 @@ namespace QRRapidoApp.Controllers public class PagamentoController : Controller { private readonly IPlanService _planService; + private readonly AdDisplayService _adDisplayService; private readonly IUserService _userService; private readonly StripeService _stripeService; private readonly ILogger _logger; - public PagamentoController(IPlanService planService, IUserService userService, StripeService stripeService, ILogger logger) + public PagamentoController(IPlanService planService, IUserService userService, StripeService stripeService, ILogger logger, AdDisplayService adDisplayService) { _planService = planService; _userService = userService; _stripeService = stripeService; _logger = logger; + _adDisplayService = adDisplayService; } [HttpGet] @@ -30,6 +32,7 @@ namespace QRRapidoApp.Controllers { var plans = await _planService.GetActivePlansAsync(); var countryCode = GetUserCountryCode(); // Implement this method based on your needs + _adDisplayService.SetViewBagAds(ViewBag); var model = new SelecaoPlanoViewModel { @@ -75,6 +78,7 @@ namespace QRRapidoApp.Controllers [HttpGet] public IActionResult Sucesso() { + _adDisplayService.SetViewBagAds(ViewBag); ViewBag.SuccessMessage = "Pagamento concluído com sucesso! Bem-vindo ao Premium."; return View(); } @@ -82,6 +86,7 @@ namespace QRRapidoApp.Controllers [HttpGet] public IActionResult Cancelar() { + _adDisplayService.SetViewBagAds(ViewBag); ViewBag.CancelMessage = "O pagamento foi cancelado. Você pode tentar novamente a qualquer momento."; return View("SelecaoPlano"); } diff --git a/Controllers/PremiumController.cs b/Controllers/PremiumController.cs index 7bf826d..ff922d1 100644 --- a/Controllers/PremiumController.cs +++ b/Controllers/PremiumController.cs @@ -27,12 +27,14 @@ namespace QRRapidoApp.Controllers [HttpGet] public IActionResult Upgrade() { + _adDisplayService.SetViewBagAds(ViewBag); return RedirectToAction("SelecaoPlano", "Pagamento"); } [HttpGet] public async Task Dashboard() { + _adDisplayService.SetViewBagAds(ViewBag); var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (string.IsNullOrEmpty(userId)) { @@ -106,6 +108,7 @@ namespace QRRapidoApp.Controllers [HttpGet] public async Task BillingPortal() { + _adDisplayService.SetViewBagAds(ViewBag); var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (string.IsNullOrEmpty(userId)) { diff --git a/Controllers/QRController.cs b/Controllers/QRController.cs index a8b93d6..ad32379 100644 --- a/Controllers/QRController.cs +++ b/Controllers/QRController.cs @@ -17,14 +17,16 @@ namespace QRRapidoApp.Controllers private readonly AdDisplayService _adService; private readonly ILogger _logger; private readonly IStringLocalizer _localizer; + private readonly AdDisplayService _adDisplayService; - public QRController(IQRCodeService qrService, IUserService userService, AdDisplayService adService, ILogger logger, IStringLocalizer localizer) + public QRController(IQRCodeService qrService, IUserService userService, AdDisplayService adService, ILogger logger, IStringLocalizer localizer, AdDisplayService adDisplayService) { _qrService = qrService; _userService = userService; _adService = adService; _logger = logger; _localizer = localizer; + _adDisplayService = adDisplayService; } [HttpPost("GenerateRapid")] @@ -34,7 +36,7 @@ namespace QRRapidoApp.Controllers var requestId = Guid.NewGuid().ToString("N")[..8]; var userId = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; var isAuthenticated = User?.Identity?.IsAuthenticated ?? false; - + using (_logger.BeginScope(new Dictionary { ["RequestId"] = requestId, diff --git a/Services/AdDisplayService.cs b/Services/AdDisplayService.cs index e629a7c..e304bf5 100644 --- a/Services/AdDisplayService.cs +++ b/Services/AdDisplayService.cs @@ -108,5 +108,11 @@ namespace QRRapidoApp.Services _logger.LogError(ex, $"Error deactivating expired sessions: {ex.Message}"); } } + + public void SetViewBagAds(dynamic viewBag) + { + viewBag.AdSenseTag = _config["AdSense:ClientId"]; + viewBag.AdSenseEnabled = _config["AdSense:Enabled"]=="True"; + } } } \ No newline at end of file diff --git a/Views/Shared/_AdSpace.cshtml b/Views/Shared/_AdSpace.cshtml index c9c1e95..43805fe 100644 --- a/Views/Shared/_AdSpace.cshtml +++ b/Views/Shared/_AdSpace.cshtml @@ -4,9 +4,13 @@ @inject AdDisplayService AdService @inject IStringLocalizer Localizer @{ + var userId = User?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value; var showAds = await AdService.ShouldShowAds(userId); var position = ViewBag.position ?? Model?.position ?? "header"; + var tagAdSense = ViewBag.AdSenseTag; + + @Html.Raw(ViewBag.AdSenseScript); } @if (showAds) @@ -18,8 +22,8 @@
@Localizer["Advertisement"]
+ data-ad-client="@tagAdSense" + data-ad-slot="QR19750801"> break; @@ -28,8 +32,8 @@
@Localizer["Advertisement"]
+ data-ad-client="@tagAdSense" + data-ad-slot="QR19750802"> break; @@ -38,8 +42,8 @@
@Localizer["Advertisement"]
+ data-ad-client="@tagAdSense" + data-ad-slot="QR19750803"> break; @@ -48,8 +52,8 @@
@Localizer["Advertisement"]
diff --git a/Views/Shared/_Layout.cshtml b/Views/Shared/_Layout.cshtml index e928813..7c42dce 100644 --- a/Views/Shared/_Layout.cshtml +++ b/Views/Shared/_Layout.cshtml @@ -80,52 +80,57 @@ - - + @if (ViewBag.AdSenseEnabled) + { + + var tagAdSense = $"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client={ViewBag.AdSenseTag}"; + var adSenseScript = $""; + + + } diff --git a/wwwroot/js/qr-speed-generator.js b/wwwroot/js/qr-speed-generator.js index 53dcf07..50eaf51 100644 --- a/wwwroot/js/qr-speed-generator.js +++ b/wwwroot/js/qr-speed-generator.js @@ -442,13 +442,6 @@ class QRRapidoGenerator { const generationTime = ((performance.now() - this.startTime) / 1000).toFixed(1); - console.log('✅ QR code recebido do backend:', { - success: result.success, - hasBase64: !!result.qrCodeBase64, - base64Length: result.qrCodeBase64?.length || 0, - generationTime: generationTime + 's' - }); - this.displayQRResult(result, generationTime); this.updateSpeedStats(generationTime); this.trackGenerationEvent(requestData.data.type || requestData.data.get('type'), generationTime); @@ -641,23 +634,12 @@ class QRRapidoGenerator { const logoSizeSlider = document.getElementById('logo-size-slider'); const logoColorizeToggle = document.getElementById('logo-colorize-toggle'); - console.log('🎨 Preparando FormData com logo:', { - logoFile: logoUpload.files[0].name, - logoSize: logoUpload.files[0].size + ' bytes', - LogoSizePercent: logoSettings.logoSizePercent, - ApplyLogoColorization: logoSettings.applyColorization, - checkboxChecked: logoColorizeToggle?.checked, - endpoint: '/api/QR/GenerateRapidWithLogo' - }); - return { data: formData, isMultipart: true, endpoint: '/api/QR/GenerateRapidWithLogo' }; } else { - // Usar JSON para QR sem logo (método original) - console.log('📝 Preparando JSON sem logo - endpoint: /api/QR/GenerateRapid'); return { data: commonData, @@ -739,13 +721,6 @@ class QRRapidoGenerator { // CORREÇÃO: Log para debug - verificar se QR code tem logo const logoUpload = document.getElementById('logo-upload'); const hasLogo = logoUpload && logoUpload.files && logoUpload.files.length > 0; - console.log('✅ QR Code exibido:', { - hasLogo: hasLogo, - logoFile: hasLogo ? logoUpload.files[0].name : 'nenhum', - generationTime: generationTime + 's', - imageSize: result.qrCodeBase64.length + ' chars', - readabilityScore: result.readabilityInfo?.readabilityScore - }); // Show generation statistics this.showGenerationStats(generationTime); @@ -986,14 +961,6 @@ class QRRapidoGenerator { logoPreview?.classList.remove('d-none'); - // CORREÇÃO: Log detalhado do logo selecionado - console.log('📁 Logo selecionado:', { - name: file.name, - size: Math.round(file.size / 1024) + 'KB', - type: file.type, - timestamp: new Date().toLocaleTimeString() - }); - // Atualizar preview de legibilidade if (typeof this.updateLogoReadabilityPreview === 'function') { this.updateLogoReadabilityPreview(); @@ -1012,7 +979,6 @@ class QRRapidoGenerator { this.clearReadabilityPreview(); } - console.log('🗑️ Logo removido'); } } @@ -1030,8 +996,6 @@ class QRRapidoGenerator { return; } } - - console.log('Corner style selected:', selectedStyle); } applyQuickStyle(e) { @@ -1069,12 +1033,6 @@ class QRRapidoGenerator { const response = await fetch('/api/QR/GetUserStats'); if (response.ok) { const stats = await response.json(); - console.log('User stats loaded:', stats); - console.log('remainingCount:', stats.remainingCount, 'type:', typeof stats.remainingCount); - console.log('isUnlimited:', stats.isUnlimited); - - // For logged users, always show unlimited (they all have unlimited QR codes) - console.log('Calling showUnlimitedCounter directly for logged user'); this.showUnlimitedCounter(); } else { if (response.status !== 401) { @@ -1148,14 +1106,6 @@ class QRRapidoGenerator { perf.totalTime += timeFloat; perf.bestTime = Math.min(perf.bestTime, timeFloat); perf.worstTime = Math.max(perf.worstTime, timeFloat); - - // Log performance statistics for debugging - console.log('📊 Performance Update:', { - currentTime: `${generationTime}s`, - averageTime: `${(perf.totalTime / perf.totalGenerations).toFixed(1)}s`, - bestTime: `${perf.bestTime.toFixed(1)}s`, - totalGenerations: perf.totalGenerations - }); } isPremiumUser() { @@ -1474,12 +1424,10 @@ class QRRapidoGenerator { } showUnlimitedCounter() { - console.log('showUnlimitedCounter called'); const counterElement = document.querySelector('.qr-counter'); if (counterElement) { counterElement.textContent = 'QR Codes ilimitados'; counterElement.className = 'badge bg-success qr-counter'; - console.log('Set counter to: QR Codes ilimitados'); } else { console.log('Counter element not found'); } @@ -2208,7 +2156,6 @@ class QRRapidoGenerator { const hasSpecialChars = /[^-]/.test(content); if (hasSpecialChars) { - console.log('Caracteres especiais detectados, aplicando codificação UTF-8'); // Forçar codificação UTF-8 const encoder = new TextEncoder(); const decoder = new TextDecoder(); @@ -2252,24 +2199,15 @@ class QRRapidoGenerator { 'Situação especial' ]; - console.group('🧪 Teste de Codificação UTF-8'); testStrings.forEach(str => { const encoded = this.prepareContentForQR(str, 'text'); - console.log(`Original: "${str}"`); - console.log(`Codificado: "${encoded}"`); - console.log('---'); }); // Teste específico para vCard if (window.vcardGenerator) { const testName = 'João Gonçalves'; const encoded = window.vcardGenerator.encodeQuotedPrintable(testName); - console.log(`vCard Quoted-Printable test:`); - console.log(`Original: "${testName}"`); - console.log(`Encoded: "${encoded}"`); } - - console.groupEnd(); } // Rate Limiting Methods @@ -2283,10 +2221,8 @@ class QRRapidoGenerator { checkRateLimit() { // Check if user is logged in (unlimited access) const userStatus = document.getElementById('user-premium-status'); - console.log('🔍 Rate limit check - User status:', userStatus ? userStatus.value : 'not found'); if (userStatus && (userStatus.value === 'logged-in' || userStatus.value === 'premium')) { - console.log('✅ User is logged in - unlimited access'); return true; // Unlimited for logged users } @@ -2295,39 +2231,29 @@ class QRRapidoGenerator { const cookieName = 'qr_daily_count'; const rateLimitData = this.getCookie(cookieName); - console.log('📅 Today:', today); - console.log('🍪 Cookie data:', rateLimitData); - let currentData = { date: today, count: 0 }; if (rateLimitData) { try { currentData = JSON.parse(rateLimitData); - console.log('📊 Parsed data:', currentData); // Reset count if it's a new day if (currentData.date !== today) { - console.log('🔄 New day detected, resetting count'); currentData = { date: today, count: 0 }; } } catch (e) { - console.log('❌ Error parsing cookie:', e); currentData = { date: today, count: 0 }; } } else { console.log('🆕 No cookie found, starting fresh'); } - console.log('📈 Current count:', currentData.count); - // Check if limit exceeded (don't increment here) if (currentData.count >= 3) { - console.log('🚫 Rate limit exceeded'); this.showRateLimitError(); return false; } - console.log('✅ Rate limit check passed'); return true; } @@ -2520,8 +2446,6 @@ class QRRapidoGenerator { } this.updateRateDisplayCounter(); - console.log('🧹 Rate limit completely reset!'); - console.log('🍪 All cookies:', document.cookie); } } @@ -2726,13 +2650,6 @@ class DynamicQRManager { analysisContainer.style.opacity = '1'; analysisContainer.style.transform = 'translateY(0)'; }, 100); - - console.log('📊 Análise de legibilidade exibida:', { - score: readabilityInfo.readabilityScore, - level: readabilityInfo.difficultyLevel, - logoSize: readabilityInfo.logoSizePercent + '%', - tipsCount: readabilityInfo.tips?.length || 0 - }); } updateLogoReadabilityPreview() {