78 lines
2.7 KiB
C#
78 lines
2.7 KiB
C#
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);
|
||
}
|
||
}
|
||
}
|
||
}
|