From 92a8709df0481fec506e92468380e7c39742ad64 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Thu, 31 Jul 2025 20:08:23 +0800 Subject: [PATCH] :zap: Translation now with cache --- .../Translation/TranslationController.cs | 33 +++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/DysonNetwork.Sphere/Translation/TranslationController.cs b/DysonNetwork.Sphere/Translation/TranslationController.cs index 6395325..86b511c 100644 --- a/DysonNetwork.Sphere/Translation/TranslationController.cs +++ b/DysonNetwork.Sphere/Translation/TranslationController.cs @@ -1,4 +1,7 @@ using DysonNetwork.Pass.Account; +using System.Security.Cryptography; +using System.Text; +using DysonNetwork.Shared.Cache; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -6,8 +9,17 @@ namespace DysonNetwork.Sphere.Translation; [ApiController] [Route("/api/translate")] -public class TranslationController(ITranslationProvider provider) : ControllerBase +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}"); + var hashBytes = SHA256.HashData(inputBytes); + return $"{CacheKeyPrefix}{Convert.ToHexString(hashBytes)}"; + } + [HttpPost] [Authorize] public async Task> Translate([FromBody] string text, [FromQuery(Name = "lang")] string targetLanguage) @@ -15,7 +27,22 @@ public class TranslationController(ITranslationProvider provider) : ControllerBa 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."); - - return await provider.Translate(text, targetLanguage); + + // Generate cache key + var cacheKey = GenerateCacheKey(text, targetLanguage); + + // Try to get from cache first + var (found, cachedResult) = await cache.GetAsyncWithStatus(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; } } \ No newline at end of file