DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/TimeZoneService.cs

72 lines
2.5 KiB
C#
Raw Normal View History

2022-04-11 18:00:34 +05:00
using AsbCloudApp.Data;
using AsbCloudApp.Services;
2021-11-22 11:30:08 +05:00
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services
{
public class TimezoneService : ITimezoneService
2021-11-22 11:30:08 +05:00
{
private class TimeZoneInfo
2021-11-22 11:30:08 +05:00
{
2023-04-18 16:16:11 +05:00
public string? Sunrise { get; set; }
2021-11-22 11:30:08 +05:00
public double Lng { get; set; }
public double Lat { get; set; }
2023-04-18 16:16:11 +05:00
public string? CountryCode { get; set; }
2021-11-22 11:30:08 +05:00
public double GmtOffset { get; set; }
public double RawOffset { get; set; }
2023-04-18 16:16:11 +05:00
public string? Sunset { get; set; }
public string? TimezoneId { get; set; }
2021-11-22 11:30:08 +05:00
public double DstOffset { get; set; }
2023-04-18 16:16:11 +05:00
public string? CountryName { get; set; }
public string? Time { get; set; }
2021-11-22 11:30:08 +05:00
}
private const string timezoneApiUrl = "http://api.geonames.org/timezoneJSON";
private const string timezoneApiUserName = "asbautodrilling";
2021-11-22 11:30:08 +05:00
2023-04-18 16:16:11 +05:00
public SimpleTimezoneDto? GetOrDefaultByCoordinates(double latitude, double longitude)
=> GetOrDefaultByCoordinatesAsync(latitude, longitude, default).Result;
2023-04-18 16:16:11 +05:00
public async Task<SimpleTimezoneDto?> GetOrDefaultByCoordinatesAsync(double latitude, double longitude, CancellationToken token)
2021-11-22 11:30:08 +05:00
{
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}";
2021-11-22 11:30:08 +05:00
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);
2022-04-11 18:00:34 +05:00
2023-04-18 16:16:11 +05:00
if(timezoneInfo is null)
return null;
return new SimpleTimezoneDto
2021-11-22 11:30:08 +05:00
{
Hours = timezoneInfo.DstOffset,
2021-11-22 11:30:08 +05:00
IsOverride = false,
TimezoneId = timezoneInfo.TimezoneId,
2021-11-22 11:30:08 +05:00
};
}
}
}