manager-service/ManagerService/Services/WeatherSyncService.cs
2026-03-25 17:38:44 +01:00

88 lines
3.2 KiB
C#

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