using xApi.Models; using xApi.Constants; using xApi.Interfaces; using xApi.Extensions; using System.Text.Json; using System.Net.Http.Headers; namespace xApi.Providers { public class AzureServices : IAzureServices { // private readonly ILogger logger; private readonly AzureServiceConfiguration configuration; public AzureServices( ILogger logger, AzureServiceConfiguration configuration ) { // this.logger = logger; this.configuration = configuration; } /// /// Retrieve Connection Info ... /// /// /// /// public async Task GetConnectionDataAsync( CancellationToken cancellationToken = default ) { // var json = await HandleAzureRequest( method: HttpMethod.Get, cancellationToken: cancellationToken, path: AzureEndpoints.ConnectionDataEndpoint ); // var result = json.ParseJSON(); if (result is null) { // var message = "Failed to parse Azure data ..."; // logger.LogError(message); throw new InvalidOperationException(message); } // return result; } /// /// Retrieve a List of Azure Projects ... /// /// /// /// public async Task> GetProjectsAsync( CancellationToken cancellationToken = default ) { // var json = await HandleAzureRequest( method: HttpMethod.Get, cancellationToken: cancellationToken, path: AzureEndpoints.ProjectsEndpoint ); // var result = json.ParseJSON>(); if (result is null) { // var message = "Failed to parse Azure data ..."; // logger.LogError(message); throw new InvalidOperationException(message); } // return result; } /// /// Retrieve a List of Azure Repositories ... /// /// /// /// public async Task> GetRepositoriesAsync( CancellationToken cancellationToken = default ) { // var json = await HandleAzureRequest( method: HttpMethod.Get, cancellationToken: cancellationToken, path: AzureEndpoints.RepositoriesEndpoint ); // var result = json.ParseJSON>(); if (result is null) { // var message = "Failed to parse Azure data ..."; // logger.LogError(message); throw new InvalidOperationException(message); } // return result; } /// /// Retrieve Specified Work Item ... /// /// /// /// public async Task GetWorkItemAsync( long workItemId, CancellationToken cancellationToken = default ) { // // Validate ... if (workItemId <= 0) { // var message = "Invalid Args ..."; // logger.LogError(message); throw new ArgumentException(message); } // // Prepare WorkItem Path ... var path = $"{AzureEndpoints.WorkItemsBaseEndpoint}/{workItemId}"; var json = await HandleAzureRequest( path: path, method: HttpMethod.Get, cancellationToken: cancellationToken ); // var result = json.ParseJSON(); if (result is null) { // var message = "Failed to parse Azure data ..."; // logger.LogError(message); throw new InvalidOperationException(message); } // return result; } /// /// Retrieve Work Item Fields ... /// /// /// public async Task> GetWorkItemFieldsAsync( CancellationToken cancellationToken = default ) { // var json = await HandleAzureRequest( method: HttpMethod.Get, cancellationToken: cancellationToken, path: AzureEndpoints.WorkItemFieldsEndpoint ); // var result = json.ParseJSON>(); if (result is null) { // var message = "Failed to parse Azure data ..."; // logger.LogError(message); throw new InvalidOperationException(message); } // return result; } /// /// Get Specified Project's WorkItem Types ... /// /// /// /// public async Task> GetProjectWorkItemTypesAsync( Guid id, CancellationToken cancellationToken = default ) { // // Prepare Custom Path for WorkItem ... var path = $"{PrepareProjectBaseUrl(id)}/{AzureEndpoints.WorkItemTypesEndpoint.NormalizeUrlSegent()}"; // var json = await HandleAzureRequest( path: path, forceApiSuffix: false, method: HttpMethod.Get, forceJsonValidation: true, cancellationToken: cancellationToken ); // var result = json.ParseJSON>(); if (result is null) { // var message = "Failed to parse Azure data ..."; // logger.LogError(message); throw new InvalidOperationException(message); } // return result; } /// /// Get Specified WorkItem Revisions (History) ... /// /// /// /// public async Task> GetWorkItemRevisionsAsync( long workItemId, CancellationToken cancellationToken = default ) { // // Validate ... if (workItemId <= 0) { // var message = "Invalid Args ..."; // logger.LogError(message); throw new ArgumentException(message); } // // Prepare WorkItem Path ... var path = $"{AzureEndpoints.WorkItemsBaseEndpoint}/{workItemId}/revisions"; var json = await HandleAzureRequest( path: path, method: HttpMethod.Get, cancellationToken: cancellationToken ); // var result = json.ParseJSON>(); if (result is null) { // var message = "Failed to parse Azure data ..."; // logger.LogError(message); throw new InvalidOperationException(message); } // return result; } // #region Private ... /// /// Handle Running Http Requests ... /// /// /// /// /// /// /// /// /// /// private async Task HandleAzureRequest( string path, HttpMethod method, bool forceApiSuffix = true, bool forceJsonValidation = true, IDictionary? headers = null, IDictionary? queryParams = null, IDictionary? routeParams = null, CancellationToken cancellationToken = default ) { // // Validate ... var pat = configuration.Pat; if (string.IsNullOrWhiteSpace(pat)) { // var message = "Azure PAT is not configured ..."; logger.LogError(message); throw new InvalidOperationException(message); } if (string.IsNullOrWhiteSpace(path)) { // var message = "Request Path is not configured ..."; logger.LogError(message); throw new InvalidOperationException(message); } // // Create Http Client ... var result = string.Empty; using (HttpClient client = new()) { // // Add Accept ... client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); // // Add Personal Access Token ... client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String( System.Text.Encoding.ASCII.GetBytes( string.Format("{0}:{1}", "", pat)))); // // Preparing Request Path ... var url = configuration.BaseUrl; if (!url!.EndsWith('/')) { url += "/"; } // // Handle Suffix ... if (forceApiSuffix && !string.IsNullOrWhiteSpace(configuration.ApiSuffix) ) { // var suffix = configuration.ApiSuffix; if (suffix.StartsWith('/')) { suffix = suffix[1..]; } // url += $"{suffix}/"; } // // Normalize Path ... if (path.StartsWith('/')) { path = path[1..]; } // // Handle Route Params ... if (routeParams is not null && routeParams.Any() ) { // var exists = routeParams.Where(rp => path.Contains(rp.Key)); foreach (var irp in exists) { } } // // Finalize Url ... url = $"{url}{path}"; // // Applying Query String ... url = url .ApplyQueryString(queries: queryParams); // // Preparing Request ... var request = new HttpRequestMessage( method: method, requestUri: url ); // // Applying Headers ... if (headers is not null && headers.Any() ) { // foreach (var header in headers) { // if (string.IsNullOrWhiteSpace(header.Value)) { continue; } // request.Headers.Add( name: header.Key, value: header.Value ); } } // // Handle Request ... try { // using var cts = CancellationTokenSource .CreateLinkedTokenSource(cancellationToken); cts.CancelAfter(TimeSpan.FromSeconds(20)); // // Execute Request ... var response = await client.SendAsync( request: request, cancellationToken: cts.Token ); // // Validate Request ... if (!response.IsSuccessStatusCode) { // var content = await response.Content.ReadAsStringAsync(cts.Token); // logger.LogError("Azure returned HTTP {StatusCode}. Content: {Content} ...", response.StatusCode, content); throw new HttpRequestException($"Azure returned HTTP {(int)response.StatusCode} ..."); } // // Reading Content ... result = await response.Content.ReadAsStringAsync(cts.Token); } catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException || !cancellationToken.IsCancellationRequested) { // logger.LogError(ex, "Azure request timed out. Path: {Path} ...", path); throw new TimeoutException("Azure request timed out ..."); } catch (Exception ex) { // logger.LogError(ex, "Could not connect to Azure. Path: {Path} ...", path); throw; } } // // Force Json Validation ... if (forceJsonValidation) { // // Validating JSON ... try { JsonDocument.Parse(result); } catch (JsonException ex) { // logger.LogError(ex, "Azure returned non-JSON data. Path: {Path} ...", path); throw new InvalidDataException("Azure returned non-JSON data ..."); } } // return result; } private string PrepareProjectBaseUrl( Guid id ) { // var result = $"{id}/{configuration.ApiSuffix?.NormalizeUrlSegent()}"; if (result.EndsWith('/')) { result = result[..^1]; } // return result; } #endregion } }