forked from ddrilling/AsbCloudServer
71 lines
2.3 KiB
C#
71 lines
2.3 KiB
C#
using AsbCloudApp.Data;
|
|
using AsbCloudApp.Services;
|
|
using System.Net.Http;
|
|
using System.Text.Json;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace AsbCloudInfrastructure.Services;
|
|
|
|
public class TimezoneService : ITimezoneService
|
|
{
|
|
private class TimeZoneInfo
|
|
{
|
|
public string? Sunrise { get; set; }
|
|
public double Lng { get; set; }
|
|
public double Lat { get; set; }
|
|
public string? CountryCode { get; set; }
|
|
public double GmtOffset { get; set; }
|
|
public double RawOffset { get; set; }
|
|
public string? Sunset { get; set; }
|
|
public string? TimezoneId { get; set; }
|
|
public double DstOffset { get; set; }
|
|
public string? CountryName { get; set; }
|
|
public string? Time { get; set; }
|
|
}
|
|
|
|
private const string timezoneApiUrl = "http://api.geonames.org/timezoneJSON";
|
|
private const string timezoneApiUserName = "asbautodrilling";
|
|
|
|
public SimpleTimezoneDto? GetOrDefaultByCoordinates(double latitude, double longitude)
|
|
=> GetOrDefaultByCoordinatesAsync(latitude, longitude, default).Result;
|
|
|
|
public async Task<SimpleTimezoneDto?> GetOrDefaultByCoordinatesAsync(double latitude, double longitude, CancellationToken token)
|
|
{
|
|
var lat = latitude.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
|
var lng = longitude.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
|
|
|
var url =
|
|
$"{timezoneApiUrl}?lat={lat}&lng={lng}&username={timezoneApiUserName}";
|
|
|
|
using var client = new HttpClient();
|
|
|
|
var response = await client.GetAsync(url, token)
|
|
.ConfigureAwait(false);
|
|
|
|
var responseJson = await response.Content.ReadAsStringAsync(token)
|
|
.ConfigureAwait(false);
|
|
|
|
if (!(responseJson.Contains("timezoneId") && responseJson.Contains("dstOffset")))
|
|
return null;
|
|
|
|
var options = new JsonSerializerOptions
|
|
{
|
|
PropertyNameCaseInsensitive = true
|
|
};
|
|
var timezoneInfo = JsonSerializer.Deserialize<TimeZoneInfo>(responseJson, options);
|
|
|
|
if(timezoneInfo is null)
|
|
return null;
|
|
|
|
return new SimpleTimezoneDto
|
|
{
|
|
Hours = timezoneInfo.DstOffset,
|
|
IsOverride = false,
|
|
TimezoneId = timezoneInfo.TimezoneId,
|
|
};
|
|
}
|
|
|
|
|
|
}
|