Files
Atomx/Atomx.Core/Jos/LocalizationJob.cs
2025-12-13 13:11:03 +08:00

78 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 Atomx.Utils.Json;
using Hangfire;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace Atomx.Core.Jos
{
/// <summary>
/// 多语言本地化任务
/// </summary>
public class LocalizationJob
{
readonly ILogger<LocalizationJob> _logger;
public LocalizationJob(ILogger<LocalizationJob> logger)
{
_logger = logger;
}
/// <summary>
/// 如果任务失败,重试 3 次超过后删除任务60 秒内不允许并发执行
/// </summary>
[AutomaticRetry(Attempts = 3, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
[DisableConcurrentExecution(60)]
public async Task ExecuteAsync(string path, string culture, string data)
{
try
{
var translations = data.FromJson<Dictionary<string, string>>();
var fileName = $"{culture}.json";
var filePath = Path.Combine(path, fileName);
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
_logger.LogInformation("Created Resources directory: {Path}", filePath);
}
var json = await File.ReadAllTextAsync(filePath);
var fileData = JsonSerializer.Deserialize<Dictionary<string, string>>(json, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
if (fileData == null)
{
fileData = new Dictionary<string, string>();
}
foreach (var item in translations)
{
if (fileData.ContainsKey(item.Key))
{
fileData[item.Key] = item.Value;
}
else
{
fileData.Add(item.Key, item.Value);
}
}
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
json = JsonSerializer.Serialize(fileData, options);
await File.WriteAllTextAsync(filePath, json);
_logger.LogInformation("Saved localization file for culture: {Culture} with {Count} translations",
culture, translations.Count);
}
catch(Exception ex) {
_logger.LogError(ex, "Error saving localization file for culture: {Culture}", culture);
}
}
}
}