using Microsoft.AspNetCore.Mvc; using AS1024.GeoFeed.Interfaces; using AS1024.GeoFeed.GeoFeedBuilder; using Microsoft.Extensions.Caching.Memory; using AS1024.GeoFeed.Models; using System.Text; using AS1024.GeoFeed.GeoFeedLocalCache; namespace AS1024.GeoFeed.Controllers { [ApiController] [Route("[controller]")] [Route("[controller].csv")] public class GeofeedController : ControllerBase { private readonly IGeoFeedProvider builder; private readonly IMemoryCache memoryCache; private readonly IWebHostEnvironment environment; private readonly ILogger logger; private readonly GeoFeedCacheDbContext dbContext; private const string GeoFeedCacheKey = "GeoFeedData"; public GeofeedController(IGeoFeedProvider builder, IMemoryCache memoryCache, IWebHostEnvironment environment, ILogger logger, GeoFeedCacheDbContext dbContext) { this.logger = logger; this.dbContext = dbContext; this.builder = builder; this.memoryCache = memoryCache; this.environment = environment; } [HttpGet] [Route("")] public async Task Get() { try { if (!memoryCache.TryGetValue(GeoFeedCacheKey, out List? feed)) { feed = await builder.GetGeoFeedData(); if (environment.IsProduction()) { MemoryCacheEntryOptions cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(15)); memoryCache.Set(GeoFeedCacheKey, feed, cacheEntryOptions); } } return ReturnFile(feed); } catch (HttpRequestException ex) { logger.LogWarning($"Temporary failure of retrieving GeoData from upstream. {ex}"); var results = dbContext.GeoFeedCacheEntries.ToList(); List cachedData = []; results.ForEach(cachedData.Add); return ReturnFile(cachedData); } catch (Exception ex) { logger.LogError($"Geofeed generation failed. Exception: {ex}"); return StatusCode(500); } } [NonAction] private IActionResult ReturnFile(List? feed) { string csvContent = feed.ToGeoFeedCsv(); // Assuming ToGeoFeedCsv() returns a string in CSV format. byte[] contentBytes = Encoding.UTF8.GetBytes(csvContent); string contentType = "text/csv"; return new FileContentResult(contentBytes, contentType) { FileDownloadName = "geofeed.csv" }; } } }