Files
2026-11-21 17:47:56 +03:30

522 lines
16 KiB
C#

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<AzureServices> logger;
private readonly AzureServiceConfiguration configuration;
public AzureServices(
ILogger<AzureServices> logger,
AzureServiceConfiguration configuration
)
{
//
this.logger = logger;
this.configuration = configuration;
}
/// <summary>
/// Retrieve Connection Info ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<AzureConnectionDataDto> GetConnectionDataAsync(
CancellationToken cancellationToken = default
)
{
//
var json = await HandleAzureRequest(
method: HttpMethod.Get,
cancellationToken: cancellationToken,
path: AzureEndpoints.ConnectionDataEndpoint
);
//
var result = json.ParseJSON<AzureConnectionDataDto>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
/// <summary>
/// Retrieve a List of Azure Projects ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<AzureListDto<AzureProjectDto>> GetProjectsAsync(
CancellationToken cancellationToken = default
)
{
//
var json = await HandleAzureRequest(
method: HttpMethod.Get,
cancellationToken: cancellationToken,
path: AzureEndpoints.ProjectsEndpoint
);
//
var result = json.ParseJSON<AzureListDto<AzureProjectDto>>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
/// <summary>
/// Retrieve a List of Azure Repositories ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<AzureListDto<AzureRepositoryDto>> GetRepositoriesAsync(
CancellationToken cancellationToken = default
)
{
//
var json = await HandleAzureRequest(
method: HttpMethod.Get,
cancellationToken: cancellationToken,
path: AzureEndpoints.RepositoriesEndpoint
);
//
var result = json.ParseJSON<AzureListDto<AzureRepositoryDto>>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
/// <summary>
/// Retrieve Specified Work Item ...
/// </summary>
/// <param name="workItemId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<AzureWorkItemDto> 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<AzureWorkItemDto>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
/// <summary>
/// Retrieve Work Item Fields ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<AzureListDto<AzureWorkItemFieldDto>> GetWorkItemFieldsAsync(
CancellationToken cancellationToken = default
)
{
//
var json = await HandleAzureRequest(
method: HttpMethod.Get,
cancellationToken: cancellationToken,
path: AzureEndpoints.WorkItemFieldsEndpoint
);
//
var result = json.ParseJSON<AzureListDto<AzureWorkItemFieldDto>>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
/// <summary>
/// Get Specified Project's WorkItem Types ...
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<AzureListDto<AzureWorkItemTypeDto>> 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<AzureListDto<AzureWorkItemTypeDto>>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
/// <summary>
/// Get Specified WorkItem Revisions (History) ...
/// </summary>
/// <param name="workItemId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<AzureListDto<WorkItemRevisionDto>> 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<AzureListDto<WorkItemRevisionDto>>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
//
#region Private ...
/// <summary>
/// Handle Running Http Requests ...
/// </summary>
/// <param name="path"></param>
/// <param name="method"></param>
/// <param name="forceApiSuffix"></param>
/// <param name="forceJsonValidation"></param>
/// <param name="headers"></param>
/// <param name="queryParams"></param>
/// <param name="routeParams"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<string> HandleAzureRequest(
string path,
HttpMethod method,
bool forceApiSuffix = true,
bool forceJsonValidation = true,
IDictionary<string, string>? headers = null,
IDictionary<string, string>? queryParams = null,
IDictionary<string, string>? 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
}
}