54 lines
2.0 KiB
C#
54 lines
2.0 KiB
C#
using System.Text.Json;
|
|
|
|
namespace LMEMappeCatastaliApp.Services;
|
|
|
|
public sealed class AzureMapsService
|
|
{
|
|
private const string TilesetEndpoint = "https://atlas.microsoft.com/map/tileset";
|
|
private readonly HttpClient _httpClient = new()
|
|
{
|
|
Timeout = TimeSpan.FromSeconds(20)
|
|
};
|
|
private string? _validatedKey;
|
|
|
|
public AzureMapsService()
|
|
{
|
|
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LMEMappeCatastali/0.2.8");
|
|
_httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
|
}
|
|
|
|
public async Task ValidateKeyAsync(string subscriptionKey, CancellationToken cancellationToken = default)
|
|
{
|
|
var key = subscriptionKey.Trim();
|
|
if (string.IsNullOrWhiteSpace(key))
|
|
{
|
|
throw new ArgumentException("Chiave Azure Maps mancante.", nameof(subscriptionKey));
|
|
}
|
|
|
|
if (string.Equals(_validatedKey, key, StringComparison.Ordinal))
|
|
{
|
|
return;
|
|
}
|
|
|
|
var url = $"{TilesetEndpoint}?api-version=2024-04-01&tilesetId=microsoft.base.road";
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
|
request.Headers.Add("subscription-key", key);
|
|
using var response = await _httpClient.SendAsync(request, cancellationToken);
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
throw new InvalidOperationException(response.StatusCode is System.Net.HttpStatusCode.Unauthorized or System.Net.HttpStatusCode.Forbidden
|
|
? "Chiave Azure Maps non valida o priva dei permessi Render."
|
|
: $"Azure Maps ha risposto {((int)response.StatusCode)}.");
|
|
}
|
|
|
|
await using var content = await response.Content.ReadAsStreamAsync(cancellationToken);
|
|
using var payload = await JsonDocument.ParseAsync(content, cancellationToken: cancellationToken);
|
|
if (!payload.RootElement.TryGetProperty("tiles", out _))
|
|
{
|
|
throw new InvalidDataException("Azure Maps ha restituito una configurazione non valida.");
|
|
}
|
|
|
|
_validatedKey = key;
|
|
}
|
|
}
|