using MiaoYu.Api.Admin.ApplicationServices.Systems.Cos.Dtos;
using MiaoYu.Core.ApplicationServices;
using MiaoYu.Core.Cos.Configs;
using MiaoYu.Core.Cos.Models;
using MiaoYu.Core.Cos.Services;
namespace MiaoYu.Api.Admin.ApplicationServices.Systems.Cos;
///
/// 腾讯云COS服务
///
public class CosService : ApplicationService
{
private readonly ICodeCosService _codeCosService;
private readonly TencentConfig _tencentConfig;
public CosService(ICodeCosService codeCosService, TencentConfig tencentConfig)
{
_codeCosService = codeCosService;
_tencentConfig = tencentConfig;
}
///
/// 获取签名
///
///
public string GetCosSign()
{
var (sign, ex) = _codeCosService.GenerateSignURL(new CosGenerateSign());
return sign;
}
///
/// 获取临时签名
///
/// 文件名
/// 模型名称
///
public GenerateTemporaryModel GetGenerateTemporaryKey(string fileName = "", string modelName = "")
{
var cosConfig = _tencentConfig.CosConfig;
var t = new CosGenerateSign()
{
Prefixes = cosConfig.Prefixes ?? "file",
Bucket = cosConfig?.Bucket,
Region = cosConfig?.Region,
AppId = cosConfig?.AppId,
SecretId = cosConfig?.SecretId,
SecretKey = cosConfig?.SecretKey,
DurationSecond = cosConfig?.DurationSecond ?? 300
};
if (string.IsNullOrEmpty(modelName))
{
modelName = "images";
}
var tempFile = fileName;
if (!string.IsNullOrEmpty(tempFile))
{
var ext = Path.GetExtension(tempFile);
if (!string.IsNullOrEmpty(ext))
{
// 使用 UTC 时间生成时间戳文件名
tempFile = $"{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}{ext}";
}
}
var model = _codeCosService.GenerateTemporaryKey(t);
// 复制对象属性
var generateTemporaryModel = model.CopyObject() ?? new GenerateTemporaryModel();
generateTemporaryModel.Bucket = t.Bucket + "-" + t.AppId;
generateTemporaryModel.Region = t.Region;
generateTemporaryModel.Prefixes = t.Prefixes;
// 修复日期格式:yyyMMdd -> yyyyMMdd
generateTemporaryModel.FilePath = $"{t.Prefixes}/{modelName}/{DateTime.Now.ToString("yyyyMMdd")}/{tempFile}";
generateTemporaryModel.DomainName = cosConfig.DomainName;
return generateTemporaryModel;
}
}