FarmMapsApiClient/FarmmapsApi/Services/FarmmapsApiService.cs

366 lines
15 KiB
C#
Raw Normal View History

2020-03-24 08:47:08 +00:00
using System;
using System.Collections.Generic;
using System.IO;
2020-03-24 22:26:02 +00:00
using System.Net;
2020-03-24 08:47:08 +00:00
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Security.Authentication;
2020-03-24 22:26:02 +00:00
using System.Text;
2020-03-24 08:47:08 +00:00
using System.Threading.Tasks;
2020-03-24 22:26:02 +00:00
using System.Web;
2020-03-24 08:47:08 +00:00
using FarmmapsApi.Models;
using Google.Apis.Http;
using Google.Apis.Upload;
2020-03-24 22:26:02 +00:00
using IdentityModel;
2020-03-24 08:47:08 +00:00
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Winista.Mime;
2020-03-24 08:47:08 +00:00
namespace FarmmapsApi.Services
{
public class FarmmapsApiService
{
private readonly Configuration _configuration;
private readonly HttpClientSettings _httpClientSettings;
2020-03-24 08:47:08 +00:00
private readonly HttpClient _httpClient;
private readonly OpenIdConnectService _openIdConnectService;
2020-03-24 22:26:02 +00:00
public FarmmapsApiService(HttpClientSettings httpClientSettings, HttpClient httpClient,
2020-03-24 08:47:08 +00:00
OpenIdConnectService openIdConnectService, Configuration configuration)
{
_configuration = configuration;
_httpClientSettings = httpClientSettings;
2020-03-24 08:47:08 +00:00
_httpClient = httpClient;
_openIdConnectService = openIdConnectService;
_httpClient.BaseAddress = new Uri(configuration.Endpoint);
_httpClient.DefaultRequestHeaders.Add("Accept", MediaTypeNames.Application.Json);
if (!string.IsNullOrEmpty(_httpClientSettings.BearerToken))
{
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(OidcConstants.AuthenticationSchemes.AuthorizationHeaderBearer,
_httpClientSettings.BearerToken);
}
2020-03-24 08:47:08 +00:00
}
public async Task AuthenticateAsync()
{
if (_httpClient.DefaultRequestHeaders.Authorization != null &&
_httpClient.DefaultRequestHeaders.Authorization.Scheme !=
2020-03-24 22:26:02 +00:00
OidcConstants.AuthenticationSchemes.AuthorizationHeaderBearer)
2020-03-24 08:47:08 +00:00
throw new AuthenticationException("Already seems to be authenticated");
var disco = await _openIdConnectService.GetDiscoveryDocumentAsync();
var token = await _openIdConnectService.GetTokenClientCredentialsAsync(disco.TokenEndpoint,
_configuration.ClientId, _configuration.ClientSecret);
if (token.IsError)
throw new AuthenticationException(token.Error);
_httpClientSettings.BearerToken = token.AccessToken;
2020-03-24 08:47:08 +00:00
_httpClient.DefaultRequestHeaders.Authorization =
2020-03-24 22:26:02 +00:00
new AuthenticationHeaderValue(OidcConstants.AuthenticationSchemes.AuthorizationHeaderBearer,
2020-03-24 08:47:08 +00:00
token.AccessToken);
}
public async Task<string> GetCurrentUserCodeAsync()
{
var url = $"{_configuration.BasePath}/{ResourceEndpoints.CURRENTUSER_RESOURCE}";
var response = await _httpClient.GetAsync(url);
2020-03-24 08:47:08 +00:00
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
var jsonString = await response.Content.ReadAsStringAsync();
var json = JsonConvert.DeserializeObject<JObject>(jsonString);
return json["code"].Value<string>();
}
2020-03-24 22:26:02 +00:00
public async Task<List<UserRoot>> GetCurrentUserRootsAsync()
2020-03-24 08:47:08 +00:00
{
var url = $"{_configuration.BasePath}/{ResourceEndpoints.MYROOTS_RESOURCE}";
var response = await _httpClient.GetAsync(url);
2020-03-24 08:47:08 +00:00
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<UserRoot>>(jsonString);
}
2020-03-24 22:26:02 +00:00
public async Task<Item> GetItemAsync(string itemCode, string itemType = null, JObject dataFilter = null)
{
if (dataFilter == null)
return await GetItemSingleAsync(itemCode, itemType);
2020-03-24 08:47:08 +00:00
2020-03-24 22:26:02 +00:00
var items = await GetItemsAsync(itemCode, itemType, dataFilter);
return items[0];
}
2020-03-24 22:26:02 +00:00
public async Task<List<Item>> GetItemsAsync(string itemCode, string itemType = null, JObject dataFilter = null)
2020-03-24 08:47:08 +00:00
{
var url = $"{_configuration.BasePath}/{ResourceEndpoints.ITEMS_RESOURCE}";
var resourceUri = string.Format(url, itemCode);
2020-03-24 22:26:02 +00:00
var queryString = HttpUtility.ParseQueryString(string.Empty);
if (itemType != null)
2020-03-24 22:26:02 +00:00
queryString["it"] = itemType;
if (dataFilter != null)
queryString["df"] = dataFilter.ToString(Formatting.None);
2020-03-24 22:26:02 +00:00
resourceUri = (queryString.Count > 0 ? $"{resourceUri}?" : resourceUri) + queryString;
2020-03-24 08:47:08 +00:00
var response = await _httpClient.GetAsync(resourceUri);
if (!response.IsSuccessStatusCode)
2020-03-24 22:26:02 +00:00
{
if (response.StatusCode == HttpStatusCode.NotFound)
return null;
2020-03-24 08:47:08 +00:00
throw new Exception(response.ReasonPhrase);
2020-03-24 22:26:02 +00:00
}
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<Item>>(jsonString);
}
private async Task<Item> GetItemSingleAsync(string itemCode, string itemType = null)
{
var url = $"{_configuration.BasePath}/{ResourceEndpoints.ITEMS_RESOURCE}";
var resourceUri = string.Format(url, itemCode);
2020-03-24 22:26:02 +00:00
if (!string.IsNullOrEmpty(itemType))
resourceUri = $"{resourceUri}/{itemType}";
2020-03-24 22:26:02 +00:00
var response = await _httpClient.GetAsync(resourceUri);
2020-03-24 22:26:02 +00:00
if (!response.IsSuccessStatusCode)
{
if (response.StatusCode == HttpStatusCode.NotFound)
return null;
2020-03-24 22:26:02 +00:00
throw new Exception(response.ReasonPhrase);
}
2020-03-24 08:47:08 +00:00
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Item>(jsonString);
}
public async Task<List<Item>> GetItemChildrenAsync(string itemCode, string itemType = null,
JObject dataFilter = null)
2020-03-24 08:47:08 +00:00
{
var url = $"{_configuration.BasePath}/{ResourceEndpoints.ITEMS_CHILDREN_RESOURCE}";
var resourceUri = string.Format(url, itemCode);
2020-03-24 22:26:02 +00:00
var queryString = HttpUtility.ParseQueryString(string.Empty);
if (itemType != null)
2020-03-24 22:26:02 +00:00
queryString["it"] = itemType;
if (dataFilter != null)
queryString["df"] = dataFilter.ToString(Formatting.None);
2020-03-24 22:26:02 +00:00
resourceUri = (queryString.Count > 0 ? $"{resourceUri}?" : resourceUri) + queryString;
2020-03-24 08:47:08 +00:00
var response = await _httpClient.GetAsync(resourceUri);
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
var jsonString = await response.Content.ReadAsStringAsync();
2020-03-24 22:26:02 +00:00
return JsonConvert.DeserializeObject<List<Item>>(jsonString);
2020-03-24 08:47:08 +00:00
}
public async Task<Item> CreateItemAsync(ItemRequest itemRequest)
{
var jsonString = JsonConvert.SerializeObject(itemRequest);
2020-03-24 22:26:02 +00:00
var url = $"{_configuration.BasePath}/{ResourceEndpoints.ITEMS_CREATE_RESOURCE}";
var content = new StringContent(jsonString, Encoding.UTF8, MediaTypeNames.Application.Json);
var response = await _httpClient.PostAsync(url,
2020-03-24 22:26:02 +00:00
content);
2020-03-24 08:47:08 +00:00
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
2020-03-24 08:47:08 +00:00
var jsonStringResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Item>(jsonStringResponse);
}
public async Task DeleteItemAsync(string itemCode)
{
var url = $"{_configuration.BasePath}/{ResourceEndpoints.ITEMS_RESOURCE}";
var resourceUri = string.Format(url, itemCode);
2020-03-24 08:47:08 +00:00
var response = await _httpClient.DeleteAsync(resourceUri);
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
}
2020-03-24 08:47:08 +00:00
public async Task DeleteItemsAsync(IList<string> itemCodes)
{
var jsonString = JsonConvert.SerializeObject(itemCodes);
var content = new StringContent(jsonString);
var url = $"{_configuration.BasePath}/{ResourceEndpoints.ITEMS_DELETE_RESOURCE}";
var response = await _httpClient.PostAsync(url, content);
2020-03-24 08:47:08 +00:00
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
}
public async Task DownloadItemAsync(string itemCode, string filePath)
{
var url = $"{_configuration.BasePath}/{ResourceEndpoints.ITEMS_DOWNLOAD_RESOURCE}";
var resourceUri = string.Format(url, itemCode);
2020-03-24 08:47:08 +00:00
var response = await _httpClient.GetAsync(resourceUri, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode)
2020-03-24 08:47:08 +00:00
{
await using Stream streamToReadFrom = await response.Content.ReadAsStreamAsync();
await using Stream streamToWriteTo = File.Open(filePath, FileMode.Create);
await streamToReadFrom.CopyToAsync(streamToWriteTo);
}
else
{
throw new FileNotFoundException(response.ReasonPhrase);
2020-03-24 08:47:08 +00:00
}
}
public async Task<string> QueueTaskAsync(string itemCode, TaskRequest taskRequest)
{
var url = $"{_configuration.BasePath}/{ResourceEndpoints.ITEMTASK_REQUEST_RESOURCE}";
var resourceUri = string.Format(url, itemCode);
2020-03-24 08:47:08 +00:00
var jsonString = JsonConvert.SerializeObject(taskRequest);
var content = new StringContent(jsonString, Encoding.UTF8, MediaTypeNames.Application.Json);
2020-03-24 22:26:02 +00:00
var response = await _httpClient.PostAsync(resourceUri, content);
2020-03-24 08:47:08 +00:00
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
2020-03-24 08:47:08 +00:00
var jsonStringResponse = await response.Content.ReadAsStringAsync();
var json = JsonConvert.DeserializeObject<JObject>(jsonStringResponse);
2020-03-24 08:47:08 +00:00
return json["code"].Value<string>();
}
2020-03-24 22:26:02 +00:00
public async Task<List<ItemTaskStatus>> GetTasksStatusAsync(string itemCode)
2020-03-24 08:47:08 +00:00
{
var url = $"{_configuration.BasePath}/{ResourceEndpoints.ITEMTASKS_RESOURCE}";
var resourceUri = string.Format(url, itemCode);
2020-03-24 08:47:08 +00:00
var response = await _httpClient.GetAsync(resourceUri);
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<ItemTaskStatus>>(jsonString);
}
public async Task<ItemTaskStatus> GetTaskStatusAsync(string itemCode, string itemTaskCode)
{
var url = $"{_configuration.BasePath}/{ResourceEndpoints.ITEMTASK_RESOURCE}";
var resourceUri = string.Format(url, itemCode, itemTaskCode);
2020-03-24 08:47:08 +00:00
var response = await _httpClient.GetAsync(resourceUri);
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<ItemTaskStatus>(jsonString);
}
/// <summary>
/// Experimental
/// </summary>
/// <param name="filePath"></param>
/// <param name="parentItemCode"></param>
/// <param name="progressCallback"></param>
/// <returns></returns>
/// <exception cref="FileNotFoundException"></exception>
2021-04-02 14:15:44 +00:00
public async Task<UploadResults> UploadFile(string filePath, string parentItemCode, string geoJsonString,
Action<IUploadProgress> progressCallback = null)
{
if (!File.Exists(filePath))
throw new FileNotFoundException($"File not found {filePath}");
var mimeTypes = new MimeTypes();
var mimeType = mimeTypes.GetMimeTypeFromFile(filePath);
2020-06-15 18:50:43 +00:00
var mimeString = mimeType?.ToString() ?? "application/json";
await using var uploadStream = new FileStream(filePath, FileMode.OpenOrCreate);
var request = new FileRequest()
{
Name = Path.GetFileName(filePath),
ParentCode = parentItemCode,
2021-04-02 14:15:44 +00:00
Size = uploadStream.Length,
Geometry = JObject.Parse(geoJsonString)
};
using var httpClient = CreateConfigurableHttpClient(_httpClient);
var farmmapsUploader = new FarmmapsUploader(httpClient, uploadStream, request,
2020-06-15 18:50:43 +00:00
mimeString, ResourceEndpoints.ITEMS_UPLOAD_RESOURCE);
Uri location = null;
farmmapsUploader.ProgressChanged += progressCallback;
farmmapsUploader.UploadSessionData += data => location = data.UploadUri;
var progress = await farmmapsUploader.UploadAsync();
return new UploadResults(progress, location);
}
/// <summary>
/// Experimental
/// </summary>
/// <param name="filePath"></param>
/// <param name="location"></param>
/// <param name="uploadCallback"></param>
/// <returns></returns>
/// <exception cref="FileNotFoundException"></exception>
private async Task<Uri> ResumeUploadFile(string filePath, Uri location, Action<IUploadProgress> uploadCallback)
{
if (!File.Exists(filePath))
throw new FileNotFoundException($"File not found {filePath}");
await using var uploadStream = new FileStream(filePath, FileMode.OpenOrCreate);
var request = new FileRequest()
{
Name = Path.GetFileName(filePath),
ParentCode = string.Empty,
Size = uploadStream.Length
};
using var httpClient = CreateConfigurableHttpClient(_httpClient);
var farmmapsUploader = new FarmmapsUploader(httpClient, uploadStream,
request, string.Empty, ResourceEndpoints.ITEMS_UPLOAD_RESOURCE);
farmmapsUploader.ProgressChanged += uploadCallback;
await farmmapsUploader.ResumeAsync(location);
return location;
}
private ConfigurableHttpClient CreateConfigurableHttpClient(HttpClient parent)
{
var googleHttpClient = new HttpClientFactory().CreateHttpClient(new CreateHttpClientArgs
{GZipEnabled = true, ApplicationName = "FarmMaps"});
googleHttpClient.BaseAddress = parent.BaseAddress;
googleHttpClient.DefaultRequestHeaders.Add("Accept", MediaTypeNames.Application.Json);
var authHeader = parent.DefaultRequestHeaders.Authorization;
googleHttpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(authHeader.Scheme, authHeader.Parameter);
return googleHttpClient;
}
2020-03-24 08:47:08 +00:00
}
}