11using System . Globalization ;
2+ using System . Text . RegularExpressions ;
23using System . Threading . Tasks ;
4+ using System . Web ;
35using DeepL ;
46using MrMeeseeks . ResXTranslationCombinator . Utility ;
57
@@ -15,6 +17,7 @@ internal class DeepLTranslator : IDeepLTranslator
1517 private readonly ILogger _logger ;
1618 private readonly Translator _deepLClient ;
1719 private IImmutableSet < CultureInfo > ? _cachedSupportedCultureInfos ;
20+ private string ? _sourceLanguage ;
1821
1922 public DeepLTranslator (
2023 IActionInputs actionInputs ,
@@ -23,6 +26,7 @@ public DeepLTranslator(
2326 {
2427 _logger = logger ;
2528 _deepLClient = deepLClientFactory ( actionInputs . AuthKey ) ;
29+ _sourceLanguage = string . IsNullOrEmpty ( actionInputs . SourceLang ) ? null : actionInputs . SourceLang ;
2630 }
2731
2832 public bool TranslationsShouldBeCached => true ;
@@ -50,23 +54,31 @@ async Task<IImmutableSet<CultureInfo>> Inner()
5054 }
5155 }
5256
57+ private static readonly Regex HotkeyPrefixRegex = new ( "&([a-zA-Z0-9])" , RegexOptions . Compiled ) ;
58+ private static readonly Regex PlaceholderRegex = new ( "{([0-9])}" , RegexOptions . Compiled ) ;
59+ private static readonly Regex PlaceholderReverseRegex = new ( "<placeholder>([0-9])</placeholder>" , RegexOptions . Compiled ) ;
60+
5361 public async Task < string [ ] > Translate (
5462 string [ ] sourceTexts ,
5563 CultureInfo targetLanguageCode )
5664 {
5765 try
5866 {
5967 var translations = await _deepLClient . TranslateTextAsync (
60- sourceTexts ,
61- null ,
68+ sourceTexts . Select ( t => PlaceholderRegex . Replace (
69+ HttpUtility . HtmlEncode ( HotkeyPrefixRegex . Replace ( t , "$1" ) ) ,
70+ "<placeholder>$1</placeholder>" ) ) ,
71+ _sourceLanguage ,
6272 targetLanguageCode . Name ,
6373 new TextTranslateOptions
6474 {
65- PreserveFormatting = true
75+ PreserveFormatting = true ,
76+ TagHandling = "xml" ,
77+ IgnoreTags = { "placeholder" }
6678 }
6779 ) ;
6880
69- return translations . Select ( t => t . Text ) . ToArray ( ) ;
81+ return translations . Select ( t => PlaceholderReverseRegex . Replace ( HttpUtility . HtmlDecode ( t . Text ) , "{$1}" ) ) . ToArray ( ) ;
7082 }
7183 catch ( Exception exception )
7284 {
0 commit comments