HuanMengAdmin/admin-server/MiaoYu.Api.Admin/ApplicationServices/Systems/Cos/CosService.cs
2025-11-12 23:15:15 +08:00

84 lines
2.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
/// <summary>
/// 腾讯云COS服务
/// </summary>
public class CosService : ApplicationService
{
private readonly ICodeCosService _codeCosService;
private readonly TencentConfig _tencentConfig;
public CosService(ICodeCosService codeCosService, TencentConfig tencentConfig)
{
_codeCosService = codeCosService;
_tencentConfig = tencentConfig;
}
/// <summary>
/// 获取签名
/// </summary>
/// <returns></returns>
public string GetCosSign()
{
var (sign, ex) = _codeCosService.GenerateSignURL(new CosGenerateSign());
return sign;
}
/// <summary>
/// 获取临时签名
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="modelName">模型名称</param>
/// <returns></returns>
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<CodeCosGenerateTemporaryKeyEntity, GenerateTemporaryModel>() ?? 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;
}
}