Files
BeWoPlaner/Service/ServiceUtils/DistanceCalculator/GoogleDistanceMatrixAPI.cs
2023-03-17 13:53:40 +01:00

159 lines
5.2 KiB
C#

using BeWo.Data.Entities;
using BS.Shared.DataContracts;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace BeWo.Service.ServiceUtils.DistanceCalculator
{
public class GoogleDistanceMatrixApi : IDistanceAPI
{
public class Response
{
public string Status { get; set; }
[JsonProperty(PropertyName = "origin_addresses")]
public string[] OriginAddresses { get; set; }
[JsonProperty(PropertyName = "destination_addresses")]
public string[] DestinationAddresses { get; set; }
public Row[] Rows { get; set; }
public class Data
{
public int Value { get; set; }
public string Text { get; set; }
}
public class Element
{
public string Status { get; set; }
public Data Duration { get; set; }
public Data Distance { get; set; }
}
public class Row
{
public Element[] Elements { get; set; }
}
}
private string Key { get; set; }
private string Url { get; set; }
private Address[] OriginAddresses { get; set; }
private Address[] DestinationAddresses { get; set; }
public GoogleDistanceMatrixApi()
{
var appSettings = ConfigurationManager.AppSettings;
if (string.IsNullOrEmpty(appSettings["GoogleDistanceMatrixApiUrl"]))
{
throw new Exception("GoogleDistanceMatrixApiUrl is not set in AppSettings.");
}
Url = appSettings["GoogleDistanceMatrixApiUrl"];
if (string.IsNullOrEmpty(appSettings["GoogleDistanceMatrixApiKey"]))
{
throw new Exception("GoogleDistanceMatrixApiKey is not set in AppSettings.");
}
Key = appSettings["GoogleDistanceMatrixApiKey"];
}
public AddressRoute[,] GetAddressRoutes(Address[] originAddresses, Address[] destinationAddresses)
{
OriginAddresses = originAddresses;
DestinationAddresses = destinationAddresses;
var task = GetResponse();
task.Wait();
if (task.Exception is object)
{
throw task.Exception;
}
return task.Result;
}
public async Task<AddressRoute[,]> GetResponse()
{
using (var client = new HttpClient())
{
var uri = new Uri(GetRequestUrl());
HttpResponseMessage response = await client.GetAsync(uri);
if (!response.IsSuccessStatusCode)
{
throw new Exception("GoogleDistanceMatrixApi failed with status code: " + response.StatusCode);
}
else
{
var content = await response.Content.ReadAsStringAsync();
return ToAddressRouteArray(JsonConvert.DeserializeObject<Response>(content));
}
}
}
public AddressRoute[,] ToAddressRouteArray(Response response)
{
var res = new AddressRoute[OriginAddresses.Length, DestinationAddresses.Length];
for (int i = 0; i < response.Rows.Length; i++)
{
var row = response.Rows[i];
for (int j = 0; j < row.Elements.Length; j++)
{
var element = row.Elements[j];
res[i, j] = ToAddressRoute(element);
res[i, j].Address1_Oid = OriginAddresses[i].Oid.Value;
res[i, j].Address1_Version = OriginAddresses[i].Version.Value;
res[i, j].Address2_Oid = DestinationAddresses[j].Oid.Value;
res[i, j].Address2_Version = DestinationAddresses[j].Version.Value;
}
}
return res;
}
public AddressRoute ToAddressRoute(Response.Element element)
{
var res = new AddressRoute();
res.Distance_in_meter = element.Distance.Value;
res.Distance_in_meter_txt = element.Distance.Text;
res.Time_in_seconds = element.Duration.Value;
res.Time_in_seconds_txt = element.Duration.Text;
return res;
}
private string GetRequestUrl()
{
var originAddresses = OriginAddresses.Select(str => ToGoogle(str)).Select(HttpUtility.UrlEncode).ToArray();
var origins = string.Join("|", originAddresses);
var destinationAddresses = DestinationAddresses.Select(str => ToGoogle(str)).Select(HttpUtility.UrlEncode).ToArray();
var destinations = string.Join("|", destinationAddresses);
return $"{Url}?origins={origins}&destinations={destinations}&key={Key}";
}
public static string ToGoogle(Address add)
{
return $"{add.Street}, {add.PostalCode}, {add.Town}, {add.State}, {add.Country}";
}
}
}