using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Nodes;
using Dpz.Core.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Dpz.Core.Service.Network;
public class AppSettingsConfiguration:IAppSettingsConfiguration
{
private readonly HttpClient _httpClient;
private readonly ILogger<AppSettingsConfiguration> _logger;
private readonly string _appSettingsBucket;
private readonly UpyunOperator _upyunOperator;
public AppSettingsConfiguration(
HttpClient httpClient,
IConfiguration configuration,
ILogger<AppSettingsConfiguration> logger)
{
_httpClient = httpClient;
_logger = logger;
_appSettingsBucket = configuration["config:ConfigurationBucket"];
if(string.IsNullOrEmpty(_appSettingsBucket))
throw new BusinessException("configuration error,need config:ConfigurationBucket config node.");
_upyunOperator = configuration.GetSection("upyun").Get<UpyunOperator>();
if (_upyunOperator == null)
throw new BusinessException("configuration error,need upyun config node.");
}
public async Task SaveConfigurationAsync(string project, string environmentFile, byte[] buffer)
{
await SaveAppSettingsAsync($"config/{project}/{environmentFile}", buffer);
}
public async Task SaveConfigurationAsync(byte[] buffer)
{
await SaveAppSettingsAsync("config/appsettings.json", buffer);
}
public async Task<IReadOnlyCollection<AppSettingStruct>> GetConfigurationStructAsync(ICollection<string>? path = null)
{
var pathToFolder = string.Empty;
if (path != null && path.Any())
{
pathToFolder = string.Join("/", path);
}
var request = new HttpRequestMessage(HttpMethod.Get, $"/{_appSettingsBucket}/{pathToFolder}")
{
Version = new Version(2, 0)
};
request.Headers.Remove("Accept");
request.Headers.Add("Accept","application/json");
request.Headers.Add("x-list-limit","1000");
await request.SignatureAsync(_upyunOperator);
var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
_logger.LogError("upload fail,status code:{StatusCode}", response.StatusCode);
throw new BusinessException($"get configuration struct fail,response status code:{response.StatusCode}");
}
var json = await response.Content.ReadAsStringAsync();
var jsonNode = JsonNode.Parse(json);
var list = jsonNode?["files"]?.Deserialize<List<AppSettingStruct>>();
return list ?? new List<AppSettingStruct>();
}
private async Task SaveAppSettingsAsync(string uri,byte[] buffer)
{
var request = new HttpRequestMessage(HttpMethod.Put, $"/{_appSettingsBucket}/{uri}")
{
Version = new Version(2, 0)
};
await request.SignatureAsync(_upyunOperator);
request.Content = new ByteArrayContent(buffer);
var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
_logger.LogError("upload fail,status code:{StatusCode}", response.StatusCode);
throw new BusinessException($"upload fail,response status code:{response.StatusCode}");
}
}
}