WeatherSync service (to test)
This commit is contained in:
parent
d5353eea9c
commit
09b7c75dac
@ -325,71 +325,6 @@ namespace ManagerService.Controllers
|
|||||||
sectionsToReturn.Add(dto);
|
sectionsToReturn.Add(dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var weatherSections = _myInfoMateDbContext.Sections.OfType<SectionWeather>()
|
|
||||||
.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<string>();
|
|
||||||
|
|
||||||
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<CityData> cities = JsonConvert.DeserializeObject<List<CityData>>(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<75>e.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (HttpRequestException e)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Une erreur s'est produite lors de la requ<71>te HTTP : {e.Message}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Une erreur s'est produite lors de la mise <20> jour des sections de type m<>t<EFBFBD>o : {e.Message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
return new OkObjectResult(sectionsToReturn);
|
return new OkObjectResult(sectionsToReturn);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
|
|||||||
87
ManagerService/Services/WeatherSyncService.cs
Normal file
87
ManagerService/Services/WeatherSyncService.cs
Normal file
@ -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<SectionWeather>()
|
||||||
|
.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<SectionWeather>()
|
||||||
|
.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<string>();
|
||||||
|
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<List<CityData>>(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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -196,6 +196,7 @@ namespace ManagerService
|
|||||||
services.AddSingleton<NotificationService>();
|
services.AddSingleton<NotificationService>();
|
||||||
services.AddHttpClient();
|
services.AddHttpClient();
|
||||||
services.AddScoped<AgendaSyncService>();
|
services.AddScoped<AgendaSyncService>();
|
||||||
|
services.AddScoped<WeatherSyncService>();
|
||||||
|
|
||||||
var connectionString = Configuration.GetConnectionString("PostgresConnection");
|
var connectionString = Configuration.GetConnectionString("PostgresConnection");
|
||||||
|
|
||||||
@ -266,6 +267,16 @@ namespace ManagerService
|
|||||||
s => s.SyncAllAsync(),
|
s => s.SyncAllAsync(),
|
||||||
Cron.Daily());
|
Cron.Daily());
|
||||||
|
|
||||||
|
RecurringJob.AddOrUpdate<WeatherSyncService>(
|
||||||
|
"weather-sync-morning",
|
||||||
|
s => s.SyncAllAsync(),
|
||||||
|
"0 6 * * *");
|
||||||
|
|
||||||
|
RecurringJob.AddOrUpdate<WeatherSyncService>(
|
||||||
|
"weather-sync-afternoon",
|
||||||
|
s => s.SyncAllAsync(),
|
||||||
|
"0 13 * * *");
|
||||||
|
|
||||||
app.UseEndpoints(endpoints =>
|
app.UseEndpoints(endpoints =>
|
||||||
{
|
{
|
||||||
endpoints.MapControllers();
|
endpoints.MapControllers();
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user