using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using Dpz.Core.Infrastructure;
using Dpz.Core.Service.ObjectStorage.Services;
using Dpz.Core.Service.ObjectStorage.Services.Impl;
using Microsoft.Extensions.DependencyInjection;
namespace Dpz.Core.Service.ObjectStorage;
public static class ObjectStorageExtension
{
/// <summary>
/// 添加又拍云云储存
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddUpyunObjectStorage(this IServiceCollection services)
{
services.AddHttpClient<IObjectStorageOperation, ObjectStorageService>(x =>
x.BaseAddress = new Uri("https://v0.api.upyun.com")).ConfigurePrimaryHttpMessageHandler(_ =>
new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
});
return services;
}
internal static async Task SignatureAsync(this HttpRequestMessage request, UpyunOperator? upyunOperator,
string? contentMd5 = null)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
if (upyunOperator == null)
throw new ArgumentNullException(nameof(upyunOperator));
var utcNow = DateTime.UtcNow;
var pwd = upyunOperator.Password.GenerateHashMd5();
var method = request.Method.ToString().ToUpper();
var uri = request.RequestUri?.OriginalString ?? "";
var message = $"{method}&{uri}&{utcNow.ToString("R")}";
if (!string.IsNullOrEmpty(contentMd5))
{
message += "&" + contentMd5;
}
var keyBytes = Encoding.UTF8.GetBytes(pwd);
var sha1 = new HMACSHA1(keyBytes);
var byteArray = Encoding.UTF8.GetBytes(message);
var stream = new MemoryStream(byteArray);
var sha1Result = await sha1.ComputeHashAsync(stream);
var signBase64 = Convert.ToBase64String(sha1Result);
request.Headers.Authorization =
AuthenticationHeaderValue.Parse($"UPYUN {upyunOperator.Operator}:{signBase64}");
request.Headers.Date = utcNow;
}
}