forked from FarmMaps/FarmMapsApiClient
		
	Handle events.
Calculate targetn.
This commit is contained in:
		@@ -5,6 +5,7 @@
 | 
			
		||||
    </PropertyGroup>
 | 
			
		||||
 | 
			
		||||
    <ItemGroup>
 | 
			
		||||
        <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="3.1.2" />
 | 
			
		||||
        <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.2" />
 | 
			
		||||
        <PackageReference Include="Microsoft.Extensions.Http" Version="3.1.2" />
 | 
			
		||||
        <PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.2" />
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										12
									
								
								FarmmapsApi/Models/EventMessage.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								FarmmapsApi/Models/EventMessage.cs
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,12 @@
 | 
			
		||||
using System.Collections.Generic;
 | 
			
		||||
using Newtonsoft.Json.Linq;
 | 
			
		||||
 | 
			
		||||
namespace FarmmapsApi.Models
 | 
			
		||||
{
 | 
			
		||||
    public class EventMessage
 | 
			
		||||
    {
 | 
			
		||||
        public string EventType { get; set; }
 | 
			
		||||
        public string ItemCode { get; set; }
 | 
			
		||||
        public Dictionary<string, string> Attributes { get; set; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -15,6 +15,7 @@ namespace FarmmapsApi.Models
 | 
			
		||||
        public string ItemType { get; set; }
 | 
			
		||||
        public string Name { get; set; }
 | 
			
		||||
        public DateTime? DataDate { get; set; }
 | 
			
		||||
        public DateTime? DataEndDate { get; set; }
 | 
			
		||||
        public JObject Geometry { get; set; }
 | 
			
		||||
        public JObject Data { get; set; }
 | 
			
		||||
        public IList<string> Tags { get; set; }
 | 
			
		||||
 
 | 
			
		||||
@@ -7,11 +7,11 @@ namespace FarmmapsApi.Models
 | 
			
		||||
        public string TaskType { get; set; }
 | 
			
		||||
        public string Delay { get; set; }
 | 
			
		||||
        
 | 
			
		||||
        public Dictionary<string, string> attributes { get; set; }
 | 
			
		||||
        public Dictionary<string, string> attributes { get; }
 | 
			
		||||
 | 
			
		||||
        public TaskRequest()
 | 
			
		||||
        {
 | 
			
		||||
            this.attributes = new Dictionary<string, string>();
 | 
			
		||||
            attributes = new Dictionary<string, string>();
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,15 +1,20 @@
 | 
			
		||||
using System;
 | 
			
		||||
using System.Collections.Generic;
 | 
			
		||||
using System.IO;
 | 
			
		||||
using System.Net;
 | 
			
		||||
using System.Net.Http;
 | 
			
		||||
using System.Net.Http.Headers;
 | 
			
		||||
using System.Net.Mime;
 | 
			
		||||
using System.Security.Authentication;
 | 
			
		||||
using System.Text;
 | 
			
		||||
using System.Threading.Tasks;
 | 
			
		||||
using System.Web;
 | 
			
		||||
using FarmmapsApi.Models;
 | 
			
		||||
using IdentityModel;
 | 
			
		||||
using Microsoft.AspNetCore.SignalR.Client;
 | 
			
		||||
using Microsoft.Extensions.DependencyInjection;
 | 
			
		||||
using Newtonsoft.Json;
 | 
			
		||||
using Newtonsoft.Json.Linq;
 | 
			
		||||
using static IdentityModel.OidcConstants;
 | 
			
		||||
 | 
			
		||||
namespace FarmmapsApi.Services
 | 
			
		||||
{
 | 
			
		||||
@@ -18,6 +23,10 @@ namespace FarmmapsApi.Services
 | 
			
		||||
        private readonly HttpClient _httpClient;
 | 
			
		||||
        private readonly OpenIdConnectService _openIdConnectService;
 | 
			
		||||
        private readonly Configuration _configuration;
 | 
			
		||||
        
 | 
			
		||||
        private HubConnection _hubConnection;
 | 
			
		||||
 | 
			
		||||
        public event Action<EventMessage> EventCallback;
 | 
			
		||||
 | 
			
		||||
        public FarmmapsApiService(HttpClient httpClient,
 | 
			
		||||
            OpenIdConnectService openIdConnectService, Configuration configuration)
 | 
			
		||||
@@ -34,7 +43,7 @@ namespace FarmmapsApi.Services
 | 
			
		||||
        {
 | 
			
		||||
            if (_httpClient.DefaultRequestHeaders.Authorization != null &&
 | 
			
		||||
                _httpClient.DefaultRequestHeaders.Authorization.Scheme !=
 | 
			
		||||
                AuthenticationSchemes.AuthorizationHeaderBearer)
 | 
			
		||||
                OidcConstants.AuthenticationSchemes.AuthorizationHeaderBearer)
 | 
			
		||||
                throw new AuthenticationException("Already seems to be authenticated");
 | 
			
		||||
 | 
			
		||||
            var disco = await _openIdConnectService.GetDiscoveryDocumentAsync();
 | 
			
		||||
@@ -45,8 +54,25 @@ namespace FarmmapsApi.Services
 | 
			
		||||
                throw new AuthenticationException(token.Error);
 | 
			
		||||
 | 
			
		||||
            _httpClient.DefaultRequestHeaders.Authorization =
 | 
			
		||||
                new AuthenticationHeaderValue(AuthenticationSchemes.AuthorizationHeaderBearer,
 | 
			
		||||
                new AuthenticationHeaderValue(OidcConstants.AuthenticationSchemes.AuthorizationHeaderBearer,
 | 
			
		||||
                    token.AccessToken);
 | 
			
		||||
 | 
			
		||||
            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);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        public async Task<string> GetCurrentUserCodeAsync()
 | 
			
		||||
@@ -61,7 +87,7 @@ namespace FarmmapsApi.Services
 | 
			
		||||
            return json["code"].Value<string>();
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        public async Task<IEnumerable<UserRoot>> GetCurrentUserRootsAsync()
 | 
			
		||||
        public async Task<List<UserRoot>> GetCurrentUserRootsAsync()
 | 
			
		||||
        {
 | 
			
		||||
            var response = await _httpClient.GetAsync(ResourceEndpoints.MYROOTS_RESOURCE);
 | 
			
		||||
 | 
			
		||||
@@ -72,36 +98,95 @@ namespace FarmmapsApi.Services
 | 
			
		||||
 | 
			
		||||
            return JsonConvert.DeserializeObject<List<UserRoot>>(jsonString);
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        public async Task<Item> GetItemAsync(string itemCode, string itemType = null, JObject dataFilter = null)
 | 
			
		||||
        {
 | 
			
		||||
            if (dataFilter == null)
 | 
			
		||||
                return await GetItemSingleAsync(itemCode, itemType);
 | 
			
		||||
 | 
			
		||||
        public async Task<Item> GetItemAsync(string itemCode)
 | 
			
		||||
            var items = await GetItemsAsync(itemCode, itemType, dataFilter);
 | 
			
		||||
            return items[0];
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        public async Task<List<Item>> GetItemsAsync(string itemCode, string itemType = null, JObject dataFilter = null)
 | 
			
		||||
        {
 | 
			
		||||
            var resourceUri = string.Format(ResourceEndpoints.ITEMS_RESOURCE, itemCode);
 | 
			
		||||
 | 
			
		||||
            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;
 | 
			
		||||
            
 | 
			
		||||
            var response = await _httpClient.GetAsync(resourceUri);
 | 
			
		||||
 | 
			
		||||
            if (!response.IsSuccessStatusCode)
 | 
			
		||||
            {
 | 
			
		||||
                if (response.StatusCode == HttpStatusCode.NotFound)
 | 
			
		||||
                    return null;
 | 
			
		||||
                
 | 
			
		||||
                throw new Exception(response.ReasonPhrase);
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
            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);
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
            var jsonString = await response.Content.ReadAsStringAsync();
 | 
			
		||||
            return JsonConvert.DeserializeObject<Item>(jsonString);
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        public async Task<IEnumerable<Item>> GetItemChildrenAsync(string itemCode)
 | 
			
		||||
        public async Task<List<Item>> GetItemChildrenAsync(string itemCode, string itemType = null, JObject dataFilter = null)
 | 
			
		||||
        {
 | 
			
		||||
            var resourceUri = string.Format(ResourceEndpoints.ITEMS_CHILDREN_RESOURCE, itemCode);
 | 
			
		||||
            
 | 
			
		||||
            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;
 | 
			
		||||
 | 
			
		||||
            var response = await _httpClient.GetAsync(resourceUri);
 | 
			
		||||
 | 
			
		||||
            if (!response.IsSuccessStatusCode)
 | 
			
		||||
                throw new Exception(response.ReasonPhrase);
 | 
			
		||||
 | 
			
		||||
            var jsonString = await response.Content.ReadAsStringAsync();
 | 
			
		||||
            return JsonConvert.DeserializeObject<IEnumerable<Item>>(jsonString);
 | 
			
		||||
            return JsonConvert.DeserializeObject<List<Item>>(jsonString);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        public async Task<Item> CreateItemAsync(ItemRequest itemRequest)
 | 
			
		||||
        {
 | 
			
		||||
            var jsonString = JsonConvert.SerializeObject(itemRequest);
 | 
			
		||||
 | 
			
		||||
            var content = new StringContent(jsonString,  Encoding.UTF8,MediaTypeNames.Application.Json);
 | 
			
		||||
            var response = await _httpClient.PostAsync(ResourceEndpoints.ITEMS_CREATE_RESOURCE, 
 | 
			
		||||
                new StringContent(jsonString));
 | 
			
		||||
                content);
 | 
			
		||||
 | 
			
		||||
            if (!response.IsSuccessStatusCode)
 | 
			
		||||
                throw new Exception(response.ReasonPhrase);
 | 
			
		||||
@@ -151,7 +236,8 @@ namespace FarmmapsApi.Services
 | 
			
		||||
            var resourceUri = string.Format(ResourceEndpoints.ITEMTASK_REQUEST_RESOURCE, itemCode);
 | 
			
		||||
 | 
			
		||||
            var jsonString = JsonConvert.SerializeObject(taskRequest);
 | 
			
		||||
            var response = await _httpClient.PostAsync(resourceUri, new StringContent(jsonString));
 | 
			
		||||
            var content = new StringContent(jsonString,  Encoding.UTF8,MediaTypeNames.Application.Json);
 | 
			
		||||
            var response = await _httpClient.PostAsync(resourceUri, content);
 | 
			
		||||
 | 
			
		||||
            if (!response.IsSuccessStatusCode)
 | 
			
		||||
                throw new Exception(response.ReasonPhrase);
 | 
			
		||||
@@ -162,7 +248,7 @@ namespace FarmmapsApi.Services
 | 
			
		||||
            return json["code"].Value<string>();
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        public async Task<IEnumerable<ItemTaskStatus>> GetTasksStatusAsync(string itemCode)
 | 
			
		||||
        public async Task<List<ItemTaskStatus>> GetTasksStatusAsync(string itemCode)
 | 
			
		||||
        {
 | 
			
		||||
            var resourceUri = string.Format(ResourceEndpoints.ITEMTASKS_RESOURCE, itemCode);
 | 
			
		||||
            var response = await _httpClient.GetAsync(resourceUri);
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user