FarmMapsApiClient/FarmmapsApi/Services/FarmmapsApiService.cs

275 lines
11 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;
2020-03-24 22:26:02 +00:00
using IdentityModel;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.DependencyInjection;
2020-03-24 08:47:08 +00:00
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace FarmmapsApi.Services
{
public class FarmmapsApiService
{
private readonly HttpClient _httpClient;
private readonly OpenIdConnectService _openIdConnectService;
private readonly Configuration _configuration;
2020-03-24 22:26:02 +00:00
private HubConnection _hubConnection;
public event Action<EventMessage> EventCallback;
2020-03-24 08:47:08 +00:00
public FarmmapsApiService(HttpClient httpClient,
OpenIdConnectService openIdConnectService, Configuration configuration)
{
_httpClient = httpClient;
_openIdConnectService = openIdConnectService;
_configuration = configuration;
_httpClient.BaseAddress = new Uri(configuration.Endpoint);
_httpClient.DefaultRequestHeaders.Add("Accept", MediaTypeNames.Application.Json);
}
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);
_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);
2020-03-24 22:26:02 +00:00
await StartEventHub(token.AccessToken);
}
private async Task StartEventHub(string accessToken)
{
var uri = new Uri(_configuration.Endpoint);
var eventEndpoint = $"{uri.Scheme}://{uri.Host}:{uri.Port}/EventHub";
_hubConnection = new HubConnectionBuilder()
.WithUrl(eventEndpoint)
.WithAutomaticReconnect()
.AddJsonProtocol()
.Build();
_hubConnection.On("Event", (EventMessage @event) => EventCallback?.Invoke(@event));
await _hubConnection.StartAsync();
await _hubConnection.SendAsync("authenticate", accessToken);
2020-03-24 08:47:08 +00:00
}
public async Task<string> GetCurrentUserCodeAsync()
{
var response = await _httpClient.GetAsync(ResourceEndpoints.CURRENTUSER_RESOURCE);
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 response = await _httpClient.GetAsync(ResourceEndpoints.MYROOTS_RESOURCE);
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];
}
public async Task<List<Item>> GetItemsAsync(string itemCode, string itemType = null, JObject dataFilter = null)
2020-03-24 08:47:08 +00:00
{
var resourceUri = string.Format(ResourceEndpoints.ITEMS_RESOURCE, itemCode);
2020-03-24 22:26:02 +00:00
var queryString = HttpUtility.ParseQueryString(string.Empty);
if(itemType != null)
queryString["it"] = itemType;
if(dataFilter != null)
queryString["df"] = dataFilter.ToString(Formatting.None);
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 resourceUri = string.Format(ResourceEndpoints.ITEMS_RESOURCE, itemCode);
if (!string.IsNullOrEmpty(itemType))
resourceUri = $"{resourceUri}/{itemType}";
var response = await _httpClient.GetAsync(resourceUri);
if (!response.IsSuccessStatusCode)
{
if (response.StatusCode == HttpStatusCode.NotFound)
return null;
throw new Exception(response.ReasonPhrase);
}
2020-03-24 08:47:08 +00:00
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Item>(jsonString);
}
2020-03-24 22:26:02 +00:00
public async Task<List<Item>> GetItemChildrenAsync(string itemCode, string itemType = null, JObject dataFilter = null)
2020-03-24 08:47:08 +00:00
{
var resourceUri = string.Format(ResourceEndpoints.ITEMS_CHILDREN_RESOURCE, itemCode);
2020-03-24 22:26:02 +00:00
var queryString = HttpUtility.ParseQueryString(string.Empty);
if(itemType != null)
queryString["it"] = itemType;
if(dataFilter != null)
queryString["df"] = dataFilter.ToString(Formatting.None);
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 content = new StringContent(jsonString, Encoding.UTF8,MediaTypeNames.Application.Json);
2020-03-24 08:47:08 +00:00
var response = await _httpClient.PostAsync(ResourceEndpoints.ITEMS_CREATE_RESOURCE,
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);
var jsonStringResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Item>(jsonStringResponse);
}
public async Task DeleteItemAsync(string itemCode)
{
var resourceUri = string.Format(ResourceEndpoints.ITEMS_RESOURCE, itemCode);
var response = await _httpClient.DeleteAsync(resourceUri);
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
}
public async Task DeleteItemsAsync(IList<string> itemCodes)
{
var jsonString = JsonConvert.SerializeObject(itemCodes);
var content = new StringContent(jsonString);
var response = await _httpClient.PostAsync(ResourceEndpoints.ITEMS_DELETE_RESOURCE, content);
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
}
public async Task DownloadItemAsync(string itemCode, string filePath)
{
var resourceUri = string.Format(ResourceEndpoints.ITEMS_DOWNLOAD_RESOURCE, itemCode);
var response = await _httpClient.GetAsync(resourceUri, HttpCompletionOption.ResponseHeadersRead);
if(response.IsSuccessStatusCode)
{
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);
}
}
public async Task<string> QueueTaskAsync(string itemCode, TaskRequest taskRequest)
{
var resourceUri = string.Format(ResourceEndpoints.ITEMTASK_REQUEST_RESOURCE, itemCode);
var jsonString = JsonConvert.SerializeObject(taskRequest);
2020-03-24 22:26:02 +00:00
var content = new StringContent(jsonString, Encoding.UTF8,MediaTypeNames.Application.Json);
var response = await _httpClient.PostAsync(resourceUri, content);
2020-03-24 08:47:08 +00:00
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
var jsonStringResponse = await response.Content.ReadAsStringAsync();
var json = JsonConvert.DeserializeObject<JObject>(jsonStringResponse);
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 resourceUri = string.Format(ResourceEndpoints.ITEMTASKS_RESOURCE, itemCode);
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 resourceUri = string.Format(ResourceEndpoints.ITEMTASK_RESOURCE, itemCode, itemTaskCode);
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);
}
}
}