using Microsoft.AspNetCore.Mvc; using Google.Apis.AnalyticsData.v1beta; using Google.Apis.AnalyticsData.v1beta.Data; using Google.Apis.Auth.OAuth2; using Google.Apis.Services; using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; namespace YourApp.Controllers { [ApiController] [Route("api/[controller]")] public class VisitorController : ControllerBase { private readonly IMemoryCache _cache; private static string[] Scopes = { AnalyticsDataService.Scope.AnalyticsReadonly }; private static string ApplicationName = "web-dlh"; private static string PropertyId = "493898388"; private static readonly TimeSpan CacheDuration = TimeSpan.FromMinutes(30); public VisitorController(IMemoryCache cache) { _cache = cache; } private static string GetCredentialsPath() { return Path.Combine( Directory.GetCurrentDirectory(), "AppData", "web-dlh-cd5131789ece.json" ); } // Endpoint to get daily visitor count [HttpGet("daily-visitor")] public async Task GetDailyVisitor() { try { var visitorCount = await GetVisitorCountAsync("yesterday", "yesterday"); return Ok(new { dailyVisitorCount = visitorCount }); } catch (Exception ex) { return StatusCode(500, new { message = "Error fetching daily visitor data", details = ex.Message }); } } // Endpoint to get monthly visitor count [HttpGet("monthly-visitor")] public async Task GetMonthlyVisitor() { try { var visitorCount = await GetVisitorCountAsync("30daysAgo", "yesterday"); return Ok(new { monthlyVisitorCount = visitorCount }); } catch (Exception ex) { return StatusCode(500, new { message = "Error fetching monthly visitor data", details = ex.Message }); } } // Endpoint to get both daily and monthly visitor counts [HttpGet("visitor-stats")] public async Task GetVisitorStats() { const string cacheKey = "visitor_stats"; try { // Check cache first if (_cache.TryGetValue(cacheKey, out var cachedStats)) { return Ok(cachedStats); } // Fetch from GA4 var dailyTask = GetVisitorCountAsync("yesterday", "yesterday"); var monthlyTask = GetVisitorCountAsync("30daysAgo", "yesterday"); await Task.WhenAll(dailyTask, monthlyTask); var stats = new { dailyVisitorCount = await dailyTask, monthlyVisitorCount = await monthlyTask, lastUpdated = DateTime.UtcNow }; _cache.Set(cacheKey, stats, CacheDuration); return Ok(stats); } catch (Exception ex) { if (_cache.TryGetValue(cacheKey, out var expiredStats)) { return Ok(expiredStats); } return StatusCode(500, new { message = "Error fetching visitor statistics", details = ex.Message }); } } // Private method to fetch visitor count from Google Analytics Data API private async Task GetVisitorCountAsync(string startDate, string endDate) { GoogleCredential credential; var credentialsPath = GetCredentialsPath(); Console.WriteLine($"Using credentials path: {credentialsPath}"); // Check if credentials file exists if (!System.IO.File.Exists(credentialsPath)) { throw new FileNotFoundException($"Credentials file not found at: {credentialsPath}"); } // Authenticate using Service Account using (var stream = new FileStream(credentialsPath, FileMode.Open, FileAccess.Read)) { credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes); } // Create the AnalyticsDataService instance var analyticsDataService = new AnalyticsDataService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Prepare the request for the report var request = new RunReportRequest { DateRanges = new List { new DateRange { StartDate = startDate, EndDate = endDate } }, Metrics = new List { new Metric { Name = "activeUsers" } } }; // Execute the request and get the response var response = await analyticsDataService.Properties.RunReport(request, $"properties/{PropertyId}").ExecuteAsync(); long visitorCount = 0; if (response?.Rows?.Count > 0 && response.Rows[0].MetricValues?.Count > 0) { if (long.TryParse(response.Rows[0].MetricValues[0].Value, out visitorCount)) { return visitorCount; } } return visitorCount; } [HttpPost("clear-cache")] public IActionResult ClearCache() { _cache.Remove("visitor_stats"); return Ok(new { message = "Cache cleared successfully" }); } } }