52 lines
1.4 KiB
C#
52 lines
1.4 KiB
C#
namespace IM_API.Tools
|
|
{
|
|
public static class ObjectNameGenerator
|
|
{
|
|
public static string Generate(ObjectNameContext ctx)
|
|
{
|
|
var ext = GetExtension(ctx.FileName, ctx.ContentType);
|
|
var shortId = Guid.NewGuid().ToString("N")[..12];
|
|
|
|
var parts = new List<string>
|
|
{
|
|
ctx.Biz,
|
|
ctx.Now.Year.ToString(),
|
|
ctx.Now.Month.ToString("D2")
|
|
};
|
|
|
|
if (ctx.UserId.HasValue)
|
|
{
|
|
parts.Add(ctx.UserId.Value.ToString());
|
|
}
|
|
|
|
parts.Add($"{shortId}{ext}");
|
|
|
|
return string.Join("/", parts);
|
|
}
|
|
|
|
private static string GetExtension(string fileName, string contentType)
|
|
{
|
|
var ext = Path.GetExtension(fileName);
|
|
if (!string.IsNullOrWhiteSpace(ext))
|
|
return ext.ToLowerInvariant();
|
|
|
|
return contentType switch
|
|
{
|
|
"image/jpeg" => ".jpg",
|
|
"image/png" => ".png",
|
|
"video/mp4" => ".mp4",
|
|
_ => ".bin"
|
|
};
|
|
}
|
|
}
|
|
public class ObjectNameContext
|
|
{
|
|
public string Biz { get; init; } = "IM";
|
|
public long? UserId { get; init; }
|
|
public string FileName { get; init; } = default!;
|
|
public string ContentType { get; init; } = default!;
|
|
public DateTimeOffset Now { get; init; } = DateTimeOffset.UtcNow;
|
|
}
|
|
|
|
}
|