2022-09-17 10:30:02 +00:00
|
|
|
|
using DataModel.Database;
|
|
|
|
|
using DeepL;
|
|
|
|
|
|
|
|
|
|
namespace Processor;
|
|
|
|
|
|
|
|
|
|
public static class DeepL
|
|
|
|
|
{
|
|
|
|
|
private static bool DEEPL_NOT_AVAILABLE = false;
|
|
|
|
|
|
|
|
|
|
public readonly record struct DeepLUsage(bool Enabled, long CharacterCount, long CharacterLimit, bool AuthIssue = false);
|
|
|
|
|
|
|
|
|
|
public static async Task<DeepLUsage> GetUsage()
|
|
|
|
|
{
|
|
|
|
|
if(DEEPL_NOT_AVAILABLE)
|
|
|
|
|
return new DeepLUsage(false, 0, 1);
|
|
|
|
|
|
|
|
|
|
if (await AppSettings.GetDeepLMode() == SettingDeepLMode.DISABLED)
|
|
|
|
|
return new DeepLUsage(false, 0, 1);
|
|
|
|
|
|
|
|
|
|
var deepLAPIKey = await AppSettings.GetDeepLAPIKey();
|
|
|
|
|
if(string.IsNullOrWhiteSpace(deepLAPIKey))
|
|
|
|
|
return new DeepLUsage(false, 0, 1);
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using var deepl = new Translator(deepLAPIKey);
|
|
|
|
|
var usage = await deepl.GetUsageAsync();
|
|
|
|
|
|
|
|
|
|
return new DeepLUsage(true, usage.Character!.Count, usage.Character.Limit);
|
|
|
|
|
}
|
2022-10-30 14:49:22 +00:00
|
|
|
|
catch (AuthorizationException)
|
2022-09-17 10:30:02 +00:00
|
|
|
|
{
|
|
|
|
|
DEEPL_NOT_AVAILABLE = true;
|
|
|
|
|
return new DeepLUsage(false, 0, 1, true);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static async Task<string> Translate(string text, string targetCulture)
|
|
|
|
|
{
|
|
|
|
|
if (DEEPL_NOT_AVAILABLE)
|
|
|
|
|
return string.Empty;
|
2022-09-26 17:19:46 +00:00
|
|
|
|
|
|
|
|
|
if (string.IsNullOrWhiteSpace(text))
|
|
|
|
|
return string.Empty;
|
2022-09-17 10:30:02 +00:00
|
|
|
|
|
|
|
|
|
if (await AppSettings.GetDeepLMode() == SettingDeepLMode.DISABLED)
|
|
|
|
|
return string.Empty;
|
|
|
|
|
|
|
|
|
|
var deepLAPIKey = await AppSettings.GetDeepLAPIKey();
|
|
|
|
|
if(string.IsNullOrWhiteSpace(deepLAPIKey))
|
|
|
|
|
return string.Empty;
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var sourceCultureIndex = await AppSettings.GetDeepLSourceCultureIndex();
|
|
|
|
|
var sourceCulture = await AppSettings.GetCultureCode(sourceCultureIndex);
|
|
|
|
|
|
2022-09-21 17:56:50 +00:00
|
|
|
|
// In case of the source culture, we cannot specify the region, so we need to remove it:
|
|
|
|
|
sourceCulture = sourceCulture.Split('-')[0];
|
|
|
|
|
|
2022-09-17 10:30:02 +00:00
|
|
|
|
using var deepl = new Translator(deepLAPIKey);
|
|
|
|
|
var translation = await deepl.TranslateTextAsync(text, sourceCulture, targetCulture);
|
|
|
|
|
|
|
|
|
|
return translation.Text;
|
|
|
|
|
}
|
2022-10-30 14:49:22 +00:00
|
|
|
|
catch (AuthorizationException)
|
2022-09-17 10:30:02 +00:00
|
|
|
|
{
|
|
|
|
|
DEEPL_NOT_AVAILABLE = true;
|
|
|
|
|
return string.Empty;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|