Refactor and expose more information

This commit was merged in pull request #1.
This commit is contained in:
2025-07-14 20:40:41 +02:00
committed by GitHub
parent 1e71c06fc3
commit 9cfbdc21d0
20 changed files with 409 additions and 162 deletions

View File

@@ -1,149 +1,18 @@
using System.Globalization;
using System.Text.Json;
using HomeApi.Handlers;
using HomeApi.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace HomeApi.Controllers;
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
public class HomeController(IMediator mediator) : ControllerBase
{
private readonly ILogger<HomeController> _logger;
private readonly IHttpClientFactory _httpClientFactory;
// get configuration from appsettings.json
private readonly ApiConfiguration _apiConfiguration;
public HomeController(ILogger<HomeController> logger, IHttpClientFactory httpClientFactory, IOptions<ApiConfiguration> apiConfiguration)
{
_logger = logger;
_apiConfiguration = apiConfiguration.Value;
_httpClientFactory = httpClientFactory;
}
[HttpGet(Name = "GetHome")]
public async Task<Home> Get()
public async Task<ActionResult<WeatherInformation>> Get()
{
var client = _httpClientFactory.CreateClient();
var cordinates = await GetCoordinatesAsync(_apiConfiguration.DefaultCity);
var auroraJson = await client.GetStringAsync($"http://api.auroras.live/v1/?type=all&lat={cordinates.Value.Latitude}&long={cordinates.Value.Longitude}&forecast=false&threeday=false");
var auroraForecast = JsonSerializer.Deserialize<AuroraForecast>(auroraJson);
var url =
$"{_apiConfiguration.BaseUrls.Weather}/forecast.json?key={_apiConfiguration.Keys.Weather}&q={cordinates.Value.Latitude},{cordinates.Value.Longitude}&days=7&lang=sv&aqi=yes&alerts=yes";
var response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var weather = JsonSerializer.Deserialize<WeatherData>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
var forecasts = weather.Forecast.Forecastday.Select(day => new Models.Forecast
{
Date = day.Date,
MaxTempC = day.Day.Maxtemp_C,
MinTempC = day.Day.Mintemp_C,
DayIcon = day.Day.Condition.Icon,
Astro = new Models.Astro {
Moon_Illumination = day.Astro.Moon_Illumination,
Moon_Phase = day.Astro.Moon_Phase,
Moonrise = day.Astro.Moonrise,
Moonset = day.Astro.Moonset,
Sunrise = day.Astro.Sunrise,
Sunset = day.Astro.Sunset
},
Day = MapSummary(day.Hour.Where(h => h.Is_Day == 1)),
Night = MapSummary(day.Hour.Where(h => h.Is_Day == 0))
}).ToList();
var result = new Home
{
CityName = cordinates.Value.name,
Current = new Models.Current
{
Date = DateTime.Now.ToString(CultureInfo.CurrentCulture),
Feelslike = weather.Current.Feelslike_C,
IsDay = weather.Current.Is_Day,
WindPerHour = weather.Current.Wind_Kph,
WindGustPerHour = weather.Current.Gust_Kph,
Temperature = weather.Current.Temp_C,
AuroraProbability = new Probability
{
Date = auroraForecast.Date,
Calculated = new Models.CalculatedProbability
{
Value = auroraForecast.Probability.Calculated.Value,
Colour = auroraForecast.Probability.Calculated.Colour,
Lat = auroraForecast.Probability.Calculated.Lat,
Long = auroraForecast.Probability.Calculated.Long
},
Colour = auroraForecast.Probability.Colour,
Value = auroraForecast.Probability.Value,
HighestProbability = new Highest
{
Colour = auroraForecast.Probability.Highest.Colour,
Lat = auroraForecast.Probability.Highest.Lat,
Long = auroraForecast.Probability.Highest.Long,
Value = auroraForecast.Probability.Highest.Value,
Date = auroraForecast.Probability.Highest.Date
}
},
},
Forecast = forecasts,
};
return result;
}
private WeatherSummary MapSummary(IEnumerable<Hour> hours)
{
if (!hours.Any())
return null;
return new WeatherSummary
{
ConditionText = hours.GroupBy(h => h.Condition.Text).OrderByDescending(g => g.Count()).First().Key,
ConditionIcon = hours.GroupBy(h => h.Condition.Icon).OrderByDescending(g => g.Count()).First().Key,
AvgTempC = Math.Round(hours.Average(h => h.Temp_C), 1),
AvgFeelslikeC = Math.Round(hours.Average(h => h.Feelslike_C), 1),
TotalChanceOfRain = (int)Math.Round(hours.Average(h => h.Chance_Of_Rain)),
TotalChanceOfSnow = (int)Math.Round(hours.Average(h => h.Chance_Of_Snow))
};
}
public async Task<(double Latitude, double Longitude, string name)?> GetCoordinatesAsync(string address)
{
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("User-Agent", "dotnet-geocoder-app");
var url = $"https://nominatim.openstreetmap.org/search?q={Uri.EscapeDataString(address)}&format=json&limit=1";
var response = await client.GetAsync(url);
if (!response.IsSuccessStatusCode)
return null;
var content = await response.Content.ReadAsStringAsync();
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var results = JsonSerializer.Deserialize<NominatimResult[]>(content, options);
if (!(results?.Length > 0))
return null;
var lat = double.Parse(results[0].Lat);
var lon = double.Parse(results[0].Lon);
var name = results[0].name;
return (lat, lon, name);
}
private class NominatimResult
{
public string Lat { get; set; }
public string Lon { get; set; }
public string name { get; set; }
var result = await mediator.Send(new GetWeather.Command());
return Ok(result);
}
}

View File

@@ -0,0 +1,129 @@
using System.Globalization;
using HomeApi.Models;
using HomeApi.Models.Response;
using AirQuality = HomeApi.Models.AirQuality;
namespace HomeApi.Extensions;
public static class ContractExtensions
{
/// <summary>
/// Converts weather related data into a <see cref="WeatherInformation"/> contract.
/// </summary>
/// <param name="weather">The weather data to map.</param>
/// <param name="locationName">The name of the location.</param>
/// <param name="auroraForecast">Optional aurora forecast data.</param>
/// <param name="forecasts">A list of weather forecasts.</param>
/// <returns>
/// A <see cref="WeatherInformation"/> object populated with current weather, aurora probability, and forecast information.
/// </returns>
public static WeatherInformation ToContract(
this WeatherData weather,
string locationName,
AuroraForecastApiResponse? auroraForecast,
List<Models.Forecast> forecasts)
{
return new WeatherInformation
{
CityName = locationName,
Current = new Models.Current
{
Date = DateTime.Now.ToString(CultureInfo.CurrentCulture),
Feelslike = weather.Current.Feelslike_C,
IsDay = weather.Current.Is_Day,
WindPerMeterSecond = ConvertToMeterPerSecond(weather.Current.Wind_Kph),
WindGustPerMeterSecond = ConvertToMeterPerSecond(weather.Current.Gust_Kph),
Temperature = weather.Current.Temp_C,
LastUpdated = weather.Current.Last_Updated,
Cloud = weather.Current.Cloud,
WindDirection = weather.Current.Wind_Dir,
WeatherDataLocation = new Models.Location
{
Name = weather.Location.Name,
Region = weather.Location.Region,
Country = weather.Location.Country,
Lat = weather.Location.Lat,
Lon = weather.Location.Lon
},
AirQuality = new AirQuality
{
Co = weather.Current.Air_Quality.Co, // Carbon Monoxide
No2 = weather.Current.Air_Quality.No2, // Nitrogen Dioxide
O3 = weather.Current.Air_Quality.O3, // Ozone
So2 = weather.Current.Air_Quality.So2, // Sulfur Dioxide
Pm10 = weather.Current.Air_Quality.Pm10, // Particulate Matter 10 micrometers or less
Pm2_5 = weather.Current.Air_Quality.Pm2_5, // Particulate Matter 2.5 micrometers or less
},
AuroraProbability = new Probability
{
Date = auroraForecast.Date,
Calculated = new CalculatedProbability
{
Value = auroraForecast.Probability.Calculated.Value,
Colour = auroraForecast.Probability.Calculated.Colour,
Lat = auroraForecast.Probability.Calculated.Lat,
Long = auroraForecast.Probability.Calculated.Long
},
Colour = auroraForecast.Probability.Colour,
Value = auroraForecast.Probability.Value,
HighestProbability = new Highest
{
Colour = auroraForecast.Probability.Highest.Colour,
Lat = auroraForecast.Probability.Highest.Lat,
Long = auroraForecast.Probability.Highest.Long,
Value = auroraForecast.Probability.Highest.Value,
Date = auroraForecast.Probability.Highest.Date
}
}
},
Forecast = forecasts
};
double ConvertToMeterPerSecond(double value = 0)
{
if (value > 0)
return value / 3.6;
return value;
}
}
public static Models.Forecast ToForecast(this ForecastDay day)
{
return new Models.Forecast
{
Date = day.Date,
MaxTempC = day.Day.Maxtemp_C,
MinTempC = day.Day.Mintemp_C,
DayIcon = day.Day.Condition.Icon,
Astro = new Models.Astro
{
Moon_Illumination = day.Astro.Moon_Illumination,
Moon_Phase = day.Astro.Moon_Phase,
Moonrise = day.Astro.Moonrise,
Moonset = day.Astro.Moonset,
Sunrise = day.Astro.Sunrise,
Sunset = day.Astro.Sunset
},
Day = ToWeatherSummary(day.Hour.Where(h => h.Is_Day == 1).ToList()),
Night = ToWeatherSummary(day.Hour.Where(h => h.Is_Day == 0).ToList())
};
}
private static WeatherSummary? ToWeatherSummary(List<Hour> hours)
{
if (hours.Count == 0)
return null;
return new WeatherSummary
{
ConditionText = hours.GroupBy(h => h.Condition.Text).OrderByDescending(g => g.Count()).First().Key,
ConditionIcon = hours.GroupBy(h => h.Condition.Icon).OrderByDescending(g => g.Count()).First().Key,
AvgTempC = Math.Round(hours.Average(h => h.Temp_C), 1),
AvgFeelslikeC = Math.Round(hours.Average(h => h.Feelslike_C), 1),
TotalChanceOfRain = (int)Math.Round(hours.Average(h => h.Chance_Of_Rain)),
TotalChanceOfSnow = (int)Math.Round(hours.Average(h => h.Chance_Of_Snow))
};
}
}

View File

@@ -0,0 +1,17 @@
using HomeApi.Models.Configuration;
using Microsoft.Extensions.Options;
namespace HomeApi.Extensions;
public static class IntegrationExtensions
{
public static void ConfigureBaseAddress(this IHttpClientBuilder builder,
Func<ApiConfiguration, string> getBaseUrl)
{
builder.ConfigureHttpClient((serviceProvider, client) =>
{
var config = serviceProvider.GetRequiredService<IOptions<ApiConfiguration>>().Value;
client.BaseAddress = new Uri(getBaseUrl(config));
});
}
}

View File

@@ -0,0 +1,50 @@
using HomeApi.Extensions;
using HomeApi.Integration;
using HomeApi.Models;
using HomeApi.Models.Configuration;
using MediatR;
using Microsoft.Extensions.Options;
namespace HomeApi.Handlers;
public static class GetWeather
{
public record Command : IRequest<WeatherInformation>;
public class Handler : IRequestHandler<Command, WeatherInformation>
{
private readonly ApiConfiguration _apiConfiguration;
private readonly ILogger<Handler> _logger;
private readonly IGeocodingService _geocodingService;
private readonly IAuroraService _auroraService;
private readonly IWeatherService _weatherService;
public Handler(
IOptions<ApiConfiguration> apiConfiguration,
ILogger<Handler> logger,
IGeocodingService geocodingService,
IAuroraService auroraService,
IWeatherService weatherService)
{
_apiConfiguration = apiConfiguration.Value;
_logger = logger;
_geocodingService = geocodingService;
_auroraService = auroraService;
_weatherService = weatherService;
}
public async Task<WeatherInformation> Handle(Command request, CancellationToken cancellationToken)
{
var coordinates = await _geocodingService.GetCoordinatesAsync(_apiConfiguration.DefaultCity);
if (coordinates is null)
throw new Exception("Coordinates not found");
var aurora = await _auroraService.GetAuroraForecastAsync(coordinates.Lat, coordinates.Lon);
var weather = await _weatherService.GetWeatherAsync(coordinates.Lat, coordinates.Lon);
var forecasts = weather.Forecast.Forecastday.Select(day => day.ToForecast()).ToList();
return weather.ToContract(coordinates.Name, aurora, forecasts);
}
}
}

View File

@@ -8,7 +8,10 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MediatR" Version="13.0.0" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.7"/>
<PackageReference Include="Refit.HttpClientFactory" Version="8.0.0" />
<PackageReference Include="Scalar.AspNetCore" Version="2.5.6" />
</ItemGroup>

View File

@@ -0,0 +1,17 @@
using HomeApi.Integration.Client;
using HomeApi.Models.Response;
namespace HomeApi.Integration;
public interface IAuroraService
{
Task<AuroraForecastApiResponse> GetAuroraForecastAsync(string lat, string lon);
}
public class AuroraService(IAuroraClient auroraApi) : IAuroraService
{
public Task<AuroraForecastApiResponse> GetAuroraForecastAsync(string lat, string lon)
{
return auroraApi.GetForecastAsync(latitude: lat, longitude: lon);
}
}

View File

@@ -0,0 +1,15 @@
using HomeApi.Models.Response;
using Refit;
namespace HomeApi.Integration.Client;
public interface IAuroraClient
{
[Get("/v1/")]
Task<AuroraForecastApiResponse> GetForecastAsync(
[AliasAs("type")] string type = "all",
[AliasAs("lat")] string latitude = "0",
[AliasAs("long")] string longitude = "0",
[AliasAs("forecast")] string forecast = "false",
[AliasAs("threeday")] string threeDay = "false");
}

View File

@@ -0,0 +1,13 @@
using HomeApi.Models.Response;
using Refit;
namespace HomeApi.Integration.Client;
public interface INominatimClient
{
[Get("/search")]
Task<List<NomatimApiResponse>> SearchAsync(
[AliasAs("q")] string query,
[AliasAs("format")] string format = "json",
[AliasAs("limit")] int limit = 1);
}

View File

@@ -0,0 +1,17 @@
using HomeApi.Models.Response;
namespace HomeApi.Integration.Client;
using Refit;
public interface IWeatherClient
{
[Get("/forecast.json")]
Task<WeatherData> GetForecastAsync(
[AliasAs("key")] string apiKey,
[AliasAs("q")] string coordinates,
[AliasAs("days")] int days = 7,
[AliasAs("lang")] string language = "sv",
[AliasAs("aqi")] string aqi = "yes",
[AliasAs("alerts")] string alerts = "yes");
}

View File

@@ -0,0 +1,19 @@
using HomeApi.Integration.Client;
using HomeApi.Models.Response;
namespace HomeApi.Integration;
public interface IGeocodingService
{
Task<NomatimApiResponse?> GetCoordinatesAsync(string address);
}
public class GeocodingService(INominatimClient nominatimApi) : IGeocodingService
{
public async Task<NomatimApiResponse?> GetCoordinatesAsync(string address)
{
var results = await nominatimApi.SearchAsync(address);
return results.FirstOrDefault();
}
}

View File

@@ -0,0 +1,22 @@
using HomeApi.Integration.Client;
using HomeApi.Models.Configuration;
using HomeApi.Models.Response;
using Microsoft.Extensions.Options;
namespace HomeApi.Integration;
public interface IWeatherService
{
Task<WeatherData> GetWeatherAsync(string lat, string lon);
}
public class WeatherService(IWeatherClient weatherApi, IOptions<ApiConfiguration> options) : IWeatherService
{
private readonly ApiConfiguration _apiConfig = options.Value;
public Task<WeatherData> GetWeatherAsync(string lat, string lon)
{
var location = $"{lat},{lon}";
return weatherApi.GetForecastAsync(_apiConfig.Keys.Weather, location);
}
}

View File

@@ -1,4 +1,4 @@
namespace HomeApi;
namespace HomeApi.Models.Configuration;
public class ApiConfiguration
{
@@ -10,11 +10,13 @@ public class ApiConfiguration
public class BaseUrls
{
public string Weather { get; set; } = string.Empty;
public string SL { get; set; } = string.Empty;
public string Nominatim { get; set; } = string.Empty;
public string Aurora { get; set; } = string.Empty;
}
public class Keys
{
public string Weather { get; set; } = string.Empty;
public string SL { get; set; } = string.Empty;
public string Nominatim { get; set; } = string.Empty;
public string Aurora { get; set; } = string.Empty;
}

View File

@@ -1,10 +1,8 @@
namespace HomeApi.Models;
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
public class AuroraForecast
namespace HomeApi.Models.Response;
public class AuroraForecastApiResponse
{
[JsonPropertyName("date")]
public DateTime Date { get; set; }

View File

@@ -0,0 +1,8 @@
namespace HomeApi.Models.Response;
public class NomatimApiResponse
{
public string Lat { get; set; }
public string Lon { get; set; }
public string Name { get; set; }
}

View File

@@ -1,3 +1,5 @@
namespace HomeApi.Models.Response;
public class WeatherData
{
public Location Location { get; set; }
@@ -169,4 +171,4 @@ public class Alert
public string Expires { get; set; }
public string Desc { get; set; }
public string Instruction { get; set; }
}
}

View File

@@ -1,6 +1,8 @@
using HomeApi.Models.Response;
namespace HomeApi.Models;
public class Home
public class WeatherInformation
{
public string CityName { get; set; } = string.Empty;
public Current Current { get; set; } = new();
@@ -12,12 +14,27 @@ public class Current
public string Date { get; set; }
public double Feelslike { get; set; }
public int IsDay { get; set; }
public double WindPerHour { get; set; } = new();
public double WindGustPerHour { get; set; } = new();
public double Temperature { get; set; } = new();
public double WindPerMeterSecond { get; set; } = 0;
public double WindGustPerMeterSecond { get; set; } = 0;
public double Temperature { get; set; } = 0;
public string LastUpdated { get; set; } = string.Empty;
public int Cloud { get; set; }
public string WindDirection { get; set; } = string.Empty;
public Location WeatherDataLocation { get; set; } = new();
public AirQuality AirQuality { get; set; }
public Probability AuroraProbability { get; set; } = new();
}
public class Location
{
public string Name { get; set; }
public string Region { get; set; }
public string Country { get; set; }
public double Lat { get; set; }
public double Lon { get; set; }
}
public class Probability
{
public DateTime Date { get; set; }
@@ -42,8 +59,8 @@ public class Forecast
public double MinTempC { get; set; }
public double MaxTempC { get; set; }
public string DayIcon { get; set; }
public WeatherSummary Day { get; set; }
public WeatherSummary Night { get; set; }
public WeatherSummary? Day { get; set; }
public WeatherSummary? Night { get; set; }
public Astro Astro { get; set; }
}
public class Astro
@@ -56,6 +73,18 @@ public class Astro
public double? Moon_Illumination { get; set; }
}
public class AirQuality
{
public double Co { get; set; }
public double No2 { get; set; }
public double O3 { get; set; }
public double So2 { get; set; }
public double Pm2_5 { get; set; }
public double Pm10 { get; set; }
public int Us_Epa_Index { get; set; }
public int Gb_Defra_Index { get; set; }
}
public class WeatherSummary
{
public string ConditionText { get; set; }

View File

@@ -1,17 +1,16 @@
using HomeApi;
using HomeApi.Registration;
using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddHttpClient();
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Program>());
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services.Configure<ApiConfiguration>(builder.Configuration.GetSection("ApiConfiguration"));
builder.Services.AddIntegration(builder.Configuration);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();

View File

@@ -0,0 +1,36 @@
using HomeApi.Extensions;
using HomeApi.Integration;
using HomeApi.Integration.Client;
using HomeApi.Models.Configuration;
using Microsoft.Extensions.Options;
using Refit;
namespace HomeApi.Registration;
public static class RegisterIntegration
{
public static void AddIntegration(this IServiceCollection services,
IConfiguration configuration)
{
services.Configure<ApiConfiguration>(configuration.GetSection("ApiConfiguration"));
services.AddRefitClient<INominatimClient>()
.ConfigureHttpClient((sp, client) =>
{
var config = sp.GetRequiredService<IOptions<ApiConfiguration>>().Value;
client.BaseAddress = new Uri(config.BaseUrls.Nominatim);
client.DefaultRequestHeaders.Add("User-Agent", "dotnet-geocoder-app");
});
services.AddRefitClient<IAuroraClient>()
.ConfigureBaseAddress(apiConfiguration => apiConfiguration.BaseUrls.Aurora);
services.AddRefitClient<IWeatherClient>()
.ConfigureBaseAddress(apiConfiguration => apiConfiguration.BaseUrls.Weather);
services.AddScoped<IGeocodingService, GeocodingService>();
services.AddScoped<IAuroraService, AuroraService>();
services.AddScoped<IWeatherService, WeatherService>();
}
}

View File

@@ -11,9 +11,10 @@
"SL": ""
},
"BaseUrls": {
"Weather": "https://api.weatherapi.com/v1",
"SL": "NOT CONFIGURED"
"Nominatim": "https://nominatim.openstreetmap.org",
"Aurora": "http://api.auroras.live",
"Weather": "https://api.weatherapi.com/v1"
},
"DefaultCity": "Vega stockholms lan"
},
}
}

View File

@@ -11,8 +11,9 @@
"SL": ""
},
"BaseUrls": {
"Weather": "https://api.weatherapi.com/v1",
"SL": "NOT CONFIGURED"
"Nominatim": "https://nominatim.openstreetmap.org",
"Aurora": "http://api.auroras.live",
"Weather": "https://api.weatherapi.com/v1"
},
"DefaultCity": "Vega stockholms lan"
},