58 lines
2.3 KiB
C#
58 lines
2.3 KiB
C#
using System.Net;
|
|
using System.Text.Json;
|
|
|
|
namespace Dada.Supervisor;
|
|
|
|
internal static class AmapProbe
|
|
{
|
|
private static readonly HttpClient Client = new() { Timeout = TimeSpan.FromSeconds(15) };
|
|
|
|
internal static int Run(string? key)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(key))
|
|
{
|
|
Write("amap_credentials_missing", false, 0, null, null);
|
|
return 3;
|
|
}
|
|
|
|
try
|
|
{
|
|
var reverse = Call("https://restapi.amap.com/v3/geocode/regeo?location=120.6994,27.9943&extensions=base", key).GetAwaiter().GetResult();
|
|
var geocode = Call($"https://restapi.amap.com/v3/geocode/geo?address={Uri.EscapeDataString("北京市天安门")}", key).GetAwaiter().GetResult();
|
|
var success = reverse.Status == "1" && geocode.Status == "1";
|
|
Write(success ? "amap_probe_passed" : "amap_provider_rejected", success, 2, reverse.Status, geocode.Status);
|
|
return success ? 0 : 3;
|
|
}
|
|
catch (TaskCanceledException)
|
|
{
|
|
Write("amap_probe_timeout", false, 0, null, null);
|
|
return 3;
|
|
}
|
|
catch (HttpRequestException exception)
|
|
{
|
|
Write($"amap_probe_network_{exception.StatusCode?.ToString() ?? "error"}", false, 0, null, null);
|
|
return 3;
|
|
}
|
|
catch (JsonException)
|
|
{
|
|
Write("amap_probe_invalid_response", false, 0, null, null);
|
|
return 3;
|
|
}
|
|
}
|
|
|
|
private static async Task<ProbeResponse> Call(string endpoint, string key)
|
|
{
|
|
using var response = await Client.GetAsync($"{endpoint}&key={Uri.EscapeDataString(key)}");
|
|
response.EnsureSuccessStatusCode();
|
|
await using var stream = await response.Content.ReadAsStreamAsync();
|
|
using var document = await JsonDocument.ParseAsync(stream);
|
|
var root = document.RootElement;
|
|
return new ProbeResponse(root.GetProperty("status").GetString() ?? "", root.TryGetProperty("infocode", out var code) ? code.GetString() : null);
|
|
}
|
|
|
|
private static void Write(string code, bool success, int realCalls, string? reverseStatus, string? geocodeStatus) =>
|
|
Console.WriteLine(JsonSerializer.Serialize(new { code, success, real_calls = realCalls, reverse_status = reverseStatus, geocode_status = geocodeStatus }));
|
|
|
|
private sealed record ProbeResponse(string Status, string? InfoCode);
|
|
}
|