fix: adsense
Some checks failed
Deploy QR Rapido / test (push) Failing after 26s
Deploy QR Rapido / build-and-push (push) Has been skipped
Deploy QR Rapido / deploy-staging (push) Has been skipped
Deploy QR Rapido / deploy-production (push) Has been skipped

This commit is contained in:
Ricardo Carneiro 2025-08-11 19:20:39 -03:00
parent bcf9f659b4
commit 12afcb3d83
9 changed files with 113 additions and 163 deletions

View File

@ -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<IActionResult> History()
{
_adDisplayService.SetViewBagAds(ViewBag);
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userId))
{

View File

@ -32,6 +32,7 @@ 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"];
@ -59,6 +60,7 @@ namespace QRRapidoApp.Controllers
ViewBag.Title = _localizer["PrivacyPolicyTitle"];
ViewBag.Description = _localizer["PrivacyPolicyDescription"];
_adDisplayService.SetViewBagAds(ViewBag);
return View();
}
@ -74,6 +76,7 @@ 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,7 +116,7 @@ namespace QRRapidoApp.Controllers
public IActionResult Sitemap()
{
var sitemap = $@"<?xml version=""1.0"" encoding=""UTF-8""?>
<urlset xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9"">
<urlset xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9"">
<url>
<loc>https://qrrapido.site/</loc>
<lastmod>{DateTime.UtcNow:yyyy-MM-dd}</lastmod>
@ -149,7 +153,7 @@ namespace QRRapidoApp.Controllers
<changefreq>monthly</changefreq>
<priority>0.5</priority>
</url>
</urlset>";
</urlset>";
return Content(sitemap, "application/xml");
}

View File

@ -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<PagamentoController> _logger;
public PagamentoController(IPlanService planService, IUserService userService, StripeService stripeService, ILogger<PagamentoController> logger)
public PagamentoController(IPlanService planService, IUserService userService, StripeService stripeService, ILogger<PagamentoController> 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");
}

View File

@ -27,12 +27,14 @@ namespace QRRapidoApp.Controllers
[HttpGet]
public IActionResult Upgrade()
{
_adDisplayService.SetViewBagAds(ViewBag);
return RedirectToAction("SelecaoPlano", "Pagamento");
}
[HttpGet]
public async Task<IActionResult> 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<IActionResult> BillingPortal()
{
_adDisplayService.SetViewBagAds(ViewBag);
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userId))
{

View File

@ -17,14 +17,16 @@ namespace QRRapidoApp.Controllers
private readonly AdDisplayService _adService;
private readonly ILogger<QRController> _logger;
private readonly IStringLocalizer<QRRapidoApp.Resources.SharedResource> _localizer;
private readonly AdDisplayService _adDisplayService;
public QRController(IQRCodeService qrService, IUserService userService, AdDisplayService adService, ILogger<QRController> logger, IStringLocalizer<QRRapidoApp.Resources.SharedResource> localizer)
public QRController(IQRCodeService qrService, IUserService userService, AdDisplayService adService, ILogger<QRController> logger, IStringLocalizer<QRRapidoApp.Resources.SharedResource> localizer, AdDisplayService adDisplayService)
{
_qrService = qrService;
_userService = userService;
_adService = adService;
_logger = logger;
_localizer = localizer;
_adDisplayService = adDisplayService;
}
[HttpPost("GenerateRapid")]

View File

@ -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";
}
}
}

View File

@ -4,9 +4,13 @@
@inject AdDisplayService AdService
@inject IStringLocalizer<QRRapidoApp.Resources.SharedResource> 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;
<!-- AdSense -->
@Html.Raw(ViewBag.AdSenseScript);
}
@if (showAds)
@ -18,8 +22,8 @@
<div class="ad-label">@Localizer["Advertisement"]</div>
<ins class="adsbygoogle"
style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-XXXXXXXXXX"
data-ad-slot="XXXXXXXXXX"></ins>
data-ad-client="@tagAdSense"
data-ad-slot="QR19750801"></ins>
</div>
break;
@ -28,8 +32,8 @@
<div class="ad-label">@Localizer["Advertisement"]</div>
<ins class="adsbygoogle"
style="display:inline-block;width:300px;height:250px"
data-ad-client="ca-pub-XXXXXXXXXX"
data-ad-slot="YYYYYYYYYY"></ins>
data-ad-client="@tagAdSense"
data-ad-slot="QR19750802"></ins>
</div>
break;
@ -38,8 +42,8 @@
<div class="ad-label">@Localizer["Advertisement"]</div>
<ins class="adsbygoogle"
style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-XXXXXXXXXX"
data-ad-slot="ZZZZZZZZZZ"></ins>
data-ad-client="@tagAdSense"
data-ad-slot="QR19750803"></ins>
</div>
break;
@ -48,8 +52,8 @@
<div class="ad-label">@Localizer["Advertisement"]</div>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-XXXXXXXXXX"
data-ad-slot="WWWWWWWWWW"
data-ad-client="@tagAdSense"
data-ad-slot="QR19750804"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
</div>

View File

@ -123,9 +123,14 @@
};
</script>
@if (ViewBag.AdSenseEnabled)
{
var tagAdSense = $"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client={ViewBag.AdSenseTag}";
var adSenseScript = $"";
<!-- AdSense -->
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXX"
crossorigin="anonymous"></script>
<script async src='@tagAdSense' crossorigin='anonymous'></script>
}
<!-- Bootstrap 5 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

View File

@ -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() {