Files
Atomx/Atomx.Core/Jos/LocalizationJob.cs
2025-12-14 02:43:40 +08:00

97 lines
3.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.Data;
using Atomx.Data.CacheServices;
using Atomx.Utils.Json;
using Hangfire;
using Microsoft.Extensions.Logging;
using System.Security.Cryptography;
using System.Text.Json;
namespace Atomx.Core.Jos
{
/// <summary>
/// 多语言本地化任务
/// </summary>
public class LocalizationJob
{
readonly ILogger<LocalizationJob> _logger;
readonly DataContext _dbContext;
readonly ICacheService _cacheService;
public LocalizationJob(ILogger<LocalizationJob> logger, DataContext dataContext, ICacheService cacheService)
{
_logger = logger;
_dbContext = dataContext;
_cacheService = cacheService;
}
/// <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(path))
{
Directory.CreateDirectory(path);
_logger.LogInformation("Created Resources directory: {Path}", path);
}
var fileData = new Dictionary<string, string>();
if (File.Exists(filePath))
{
var json = await File.ReadAllTextAsync(filePath);
fileData = JsonSerializer.Deserialize<Dictionary<string, string>>(json, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
}) ?? new Dictionary<string, string>();
}
foreach (var item in translations)
{
fileData[item.Key] = item.Value;
}
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
var updatedJson = JsonSerializer.Serialize(fileData, options);
await File.WriteAllTextAsync(filePath, updatedJson);
// 更新文件后,更新数据库中的资源版本
string fileHash;
using (var sha256 = SHA256.Create())
using (var stream = File.OpenRead(filePath))
{
var hashBytes = sha256.ComputeHash(stream);
fileHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
}
var language = _dbContext.Languages.FirstOrDefault(l => l.Culture == culture);
if (language != null)
{
language.UpdateTime = DateTime.UtcNow;
language.ResourceVersion = fileHash;
await _dbContext.SaveChangesAsync();
await _cacheService.GetLanguageById(language.Id, language);
}
_logger.LogInformation("Saved localization file for culture: {Culture} with {Count} translations. File hash: {Hash}",
culture, translations.Count, fileHash);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error saving localization file for culture: {Culture}", culture);
}
}
}
}