From 09b7c75dac8ab5b9f0aeb634ad01790b3c89ed4f Mon Sep 17 00:00:00 2001 From: Thomas Fransolet Date: Wed, 25 Mar 2026 17:38:44 +0100 Subject: [PATCH] WeatherSync service (to test) --- .../Controllers/SectionController.cs | 65 -------------- ManagerService/Services/WeatherSyncService.cs | 87 +++++++++++++++++++ ManagerService/Startup.cs | 11 +++ 3 files changed, 98 insertions(+), 65 deletions(-) create mode 100644 ManagerService/Services/WeatherSyncService.cs diff --git a/ManagerService/Controllers/SectionController.cs b/ManagerService/Controllers/SectionController.cs index a5d653a..2bce333 100644 --- a/ManagerService/Controllers/SectionController.cs +++ b/ManagerService/Controllers/SectionController.cs @@ -325,71 +325,6 @@ namespace ManagerService.Controllers sectionsToReturn.Add(dto); } - try - { - var weatherSections = _myInfoMateDbContext.Sections.OfType() - .Where(s => s.ConfigurationId == id && !s.IsSubSection) - .ToList(); - - foreach (var weatherSection in weatherSections) - { - if (weatherSection.WeatherCity != null && weatherSection.WeatherCity.Length >= 2 && - (weatherSection.WeatherUpdatedDate == null || weatherSection.WeatherUpdatedDate.Value.AddHours(3) < DateTimeOffset.Now)) // Update all 4 hours - { - // Call Openweather api with token from appSettings and update result with json - var apiKey = _configuration.GetSection("OpenWeatherApiKey").Get(); - - if (apiKey != null && apiKey.Length > 0) - { - string url = $"http://api.openweathermap.org/geo/1.0/direct?q={weatherSection.WeatherCity}&limit=1&appid={apiKey}"; - - using (HttpClient client = new HttpClient()) - { - try - { - HttpResponseMessage response = await client.GetAsync(url); - response.EnsureSuccessStatusCode(); - string responseBody = await response.Content.ReadAsStringAsync(); - - List cities = JsonConvert.DeserializeObject>(responseBody); - - if (cities.Count > 0) - { - double lat = cities[0].Lat; - double lon = cities[0].Lon; - - //string onecallUrl = $"https://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&appid={apiKey}"; - string callUrl = $"https://api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&units=metric&appid={apiKey}"; - - HttpResponseMessage callResponse = await client.GetAsync(callUrl); - callResponse.EnsureSuccessStatusCode(); - string callResponseBody = await callResponse.Content.ReadAsStringAsync(); - - - weatherSection.WeatherUpdatedDate = DateTimeOffset.Now.ToUniversalTime(); ; - weatherSection.WeatherResult = callResponseBody; - _myInfoMateDbContext.SaveChanges(); - } - else - { - Console.WriteLine("Aucune ville trouv�e."); - } - } - catch (HttpRequestException e) - { - Console.WriteLine($"Une erreur s'est produite lors de la requ�te HTTP : {e.Message}"); - } - } - } - } - - } - } - catch (Exception e) - { - Console.WriteLine($"Une erreur s'est produite lors de la mise � jour des sections de type m�t�o : {e.Message}"); - } - return new OkObjectResult(sectionsToReturn); } else diff --git a/ManagerService/Services/WeatherSyncService.cs b/ManagerService/Services/WeatherSyncService.cs new file mode 100644 index 0000000..64f3ce7 --- /dev/null +++ b/ManagerService/Services/WeatherSyncService.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; +using ManagerService.Data; +using Manager.Interfaces.Models; +using ManagerService.Data.SubSection; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Newtonsoft.Json; +using System.Linq; + +namespace ManagerService.Services +{ + public class WeatherSyncService + { + private readonly MyInfoMateDbContext _dbContext; + private readonly IHttpClientFactory _httpClientFactory; + private readonly IConfiguration _configuration; + + public WeatherSyncService(MyInfoMateDbContext dbContext, IHttpClientFactory httpClientFactory, IConfiguration configuration) + { + _dbContext = dbContext; + _httpClientFactory = httpClientFactory; + _configuration = configuration; + } + + public async Task SyncAllAsync() + { + var sections = await _dbContext.Sections.OfType() + .Where(s => s.WeatherCity != null && s.WeatherCity.Length >= 2) + .ToListAsync(); + + foreach (var section in sections) + await SyncSectionAsync(section); + } + + public async Task SyncSectionAsync(string sectionId) + { + var section = await _dbContext.Sections.OfType() + .FirstOrDefaultAsync(s => s.Id == sectionId); + + if (section != null) + await SyncSectionAsync(section); + } + + private async Task SyncSectionAsync(SectionWeather section) + { + if (string.IsNullOrWhiteSpace(section.WeatherCity)) + return; + + var apiKey = _configuration.GetSection("OpenWeatherApiKey").Get(); + if (string.IsNullOrEmpty(apiKey)) + return; + + try + { + var client = _httpClientFactory.CreateClient(); + + string geoUrl = $"http://api.openweathermap.org/geo/1.0/direct?q={section.WeatherCity}&limit=1&appid={apiKey}"; + var geoResponse = await client.GetAsync(geoUrl); + geoResponse.EnsureSuccessStatusCode(); + var geoBody = await geoResponse.Content.ReadAsStringAsync(); + + var cities = JsonConvert.DeserializeObject>(geoBody); + if (cities == null || cities.Count == 0) + return; + + double lat = cities[0].Lat; + double lon = cities[0].Lon; + + string forecastUrl = $"https://api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&units=metric&appid={apiKey}"; + var forecastResponse = await client.GetAsync(forecastUrl); + forecastResponse.EnsureSuccessStatusCode(); + string forecastBody = await forecastResponse.Content.ReadAsStringAsync(); + + section.WeatherResult = forecastBody; + section.WeatherUpdatedDate = DateTimeOffset.UtcNow; + await _dbContext.SaveChangesAsync(); + } + catch (Exception e) + { + Console.WriteLine($"WeatherSyncService error for city '{section.WeatherCity}': {e.Message}"); + } + } + } +} diff --git a/ManagerService/Startup.cs b/ManagerService/Startup.cs index 905e110..78c02f2 100644 --- a/ManagerService/Startup.cs +++ b/ManagerService/Startup.cs @@ -196,6 +196,7 @@ namespace ManagerService services.AddSingleton(); services.AddHttpClient(); services.AddScoped(); + services.AddScoped(); var connectionString = Configuration.GetConnectionString("PostgresConnection"); @@ -266,6 +267,16 @@ namespace ManagerService s => s.SyncAllAsync(), Cron.Daily()); + RecurringJob.AddOrUpdate( + "weather-sync-morning", + s => s.SyncAllAsync(), + "0 6 * * *"); + + RecurringJob.AddOrUpdate( + "weather-sync-afternoon", + s => s.SyncAllAsync(), + "0 13 * * *"); + app.UseEndpoints(endpoints => { endpoints.MapControllers();