Files
BetterLyrics/BetterLyrics.WinUI3/BetterLyrics.WinUI3/Services/TranslationService/TranslateService.cs
2025-12-22 11:47:29 -05:00

57 lines
2.1 KiB
C#

using BetterLyrics.WinUI3.Helper;
using BetterLyrics.WinUI3.Serialization;
using BetterLyrics.WinUI3.Services.SettingsService;
using BetterLyrics.WinUI3.ViewModels;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace BetterLyrics.WinUI3.Services.TranslationService
{
public partial class TranslationService : BaseViewModel, ITranslationService
{
private readonly ISettingsService _settingsService;
private readonly HttpClient _httpClient;
public TranslationService(ISettingsService settingsService)
{
_settingsService = settingsService;
_httpClient = new HttpClient();
}
public async Task<string> TranslateTextAsync(string text, string targetLangCode, CancellationToken token)
{
if (string.IsNullOrWhiteSpace(text))
{
throw new Exception(text + " is empty or null.");
}
string? originalLangCode = LanguageHelper.DetectLanguageCode(text);
if (string.IsNullOrWhiteSpace(originalLangCode) || originalLangCode == targetLangCode)
{
return text; // No translation needed
}
if (string.IsNullOrEmpty(_settingsService.AppSettings.TranslationSettings.LibreTranslateServer))
{
throw new Exception("LibreTranslate server URL is not set in settings.");
}
var url = $"{_settingsService.AppSettings.TranslationSettings.LibreTranslateServer}/translate";
var response = await _httpClient.PostAsync(url, new FormUrlEncodedContent(
[
new("q", text),
new("source", originalLangCode),
new("target", targetLangCode),
]), token);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync(token);
var result = System.Text.Json.JsonSerializer.Deserialize(json, SourceGenerationContext.Default.LibreTranslateResponse);
return result?.TranslatedText ?? string.Empty;
}
}
}