about summary refs log tree commit diff
path: root/app/lib/translation_service/deepl.rb
diff options
context:
space:
mode:
authorChristian Schmidt <github@chsc.dk>2023-03-16 11:07:24 +0100
committerGitHub <noreply@github.com>2023-03-16 11:07:24 +0100
commitbd047acc356671727c112336bb237f979bba517d (patch)
treef65ea64df4dcf6bb93a5561bb237caf78c54153c /app/lib/translation_service/deepl.rb
parent630436ab2d84b5ed2334ad510cb9ad6253050ae5 (diff)
Replace `Status#translatable?` with language matrix in separate endpoint (#24037)
Diffstat (limited to 'app/lib/translation_service/deepl.rb')
-rw-r--r--app/lib/translation_service/deepl.rb30
1 files changed, 18 insertions, 12 deletions
diff --git a/app/lib/translation_service/deepl.rb b/app/lib/translation_service/deepl.rb
index deff95a1d..afcb7ecb2 100644
--- a/app/lib/translation_service/deepl.rb
+++ b/app/lib/translation_service/deepl.rb
@@ -17,25 +17,31 @@ class TranslationService::DeepL < TranslationService
     end
   end
 
-  def supported?(source_language, target_language)
-    source_language.in?(languages('source')) && target_language.in?(languages('target'))
+  def languages
+    source_languages = [nil] + fetch_languages('source')
+
+    # In DeepL, EN and PT are deprecated in favor of EN-GB/EN-US and PT-BR/PT-PT, so
+    # they are supported but not returned by the API.
+    target_languages = %w(en pt) + fetch_languages('target')
+
+    source_languages.index_with { |language| target_languages.without(nil, language) }
   end
 
   private
 
-  def languages(type)
-    Rails.cache.fetch("translation_service/deepl/languages/#{type}", expires_in: 7.days, race_condition_ttl: 1.minute) do
-      request(:get, "/v2/languages?type=#{type}") do |res|
-        # In DeepL, EN and PT are deprecated in favor of EN-GB/EN-US and PT-BR/PT-PT, so
-        # they are supported but not returned by the API.
-        extra = type == 'source' ? [nil] : %w(en pt)
-        languages = Oj.load(res.body_with_limit).map { |language| language['language'].downcase }
-
-        languages + extra
-      end
+  def fetch_languages(type)
+    request(:get, "/v2/languages?type=#{type}") do |res|
+      Oj.load(res.body_with_limit).map { |language| normalize_language(language['language']) }
     end
   end
 
+  def normalize_language(language)
+    subtags = language.split(/[_-]/)
+    subtags[0].downcase!
+    subtags[1]&.upcase!
+    subtags.join('-')
+  end
+
   def request(verb, path, **options)
     req = Request.new(verb, "#{base_url}#{path}", **options)
     req.add_headers(Authorization: "DeepL-Auth-Key #{@api_key}")