🐛 Fixes of translation api

This commit is contained in:
2025-07-31 20:25:04 +08:00
parent d7dcb7221f
commit 77df275ac0
4 changed files with 17 additions and 10 deletions

View File

@@ -12,7 +12,7 @@ namespace DysonNetwork.Sphere.Translation;
public class TranslationController(ITranslationProvider provider, ICacheService cache) : ControllerBase
{
private const string CacheKeyPrefix = "translation:";
private static string GenerateCacheKey(string text, string targetLanguage)
{
var inputBytes = Encoding.UTF8.GetBytes($"{text}:{targetLanguage}");
@@ -22,27 +22,31 @@ public class TranslationController(ITranslationProvider provider, ICacheService
[HttpPost]
[Authorize]
public async Task<ActionResult<string>> Translate([FromBody] string text, [FromQuery(Name = "lang")] string targetLanguage)
public async Task<ActionResult<string>> Translate(
[FromBody] string text,
[FromQuery(Name = "from")] string targetLanguage,
[FromQuery(Name = "to")] string? sourceLanguage
)
{
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
if (currentUser.PerkSubscription is null)
return StatusCode(403, "You need a subscription to use this feature.");
// Generate cache key
var cacheKey = GenerateCacheKey(text, targetLanguage);
// Try to get from cache first
var (found, cachedResult) = await cache.GetAsyncWithStatus<string>(cacheKey);
if (found && cachedResult != null)
return Ok(cachedResult);
// If not in cache, translate and cache the result
var result = await provider.Translate(text, targetLanguage);
if (!string.IsNullOrEmpty(result))
{
await cache.SetAsync(cacheKey, result, TimeSpan.FromHours(24)); // Cache for 24 hours
}
return result;
}
}