deepl-rb 3.10.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +1 -1
  3. data/CHANGELOG.md +313 -1
  4. data/README.md +225 -309
  5. data/Rakefile +17 -8
  6. data/VERSION +1 -1
  7. data/deepl-rb.gemspec +73 -86
  8. data/lib/deepl/admin_client.rb +39 -14
  9. data/lib/deepl/api.rb +3 -17
  10. data/lib/deepl/app_info.rb +0 -1
  11. data/lib/deepl/client.rb +399 -84
  12. data/lib/deepl/configuration.rb +19 -70
  13. data/lib/deepl/exceptions/authorization_failed.rb +1 -1
  14. data/lib/deepl/exceptions/connection_error.rb +10 -7
  15. data/lib/deepl/exceptions/limit_exceeded.rb +1 -1
  16. data/lib/deepl/exceptions/quota_exceeded.rb +1 -1
  17. data/lib/deepl/exceptions/request_entity_too_large.rb +1 -2
  18. data/lib/deepl/exceptions/request_error.rb +7 -0
  19. data/lib/deepl/exceptions/server_error.rb +2 -1
  20. data/lib/deepl/exceptions/translation_memory_job_error.rb +32 -0
  21. data/lib/deepl/exceptions/validation_error.rb +3 -2
  22. data/lib/deepl/requests/base.rb +129 -51
  23. data/lib/deepl/requests/correct.rb +2 -8
  24. data/lib/deepl/requests/document/upload.rb +29 -26
  25. data/lib/deepl/requests/glossary/base.rb +30 -0
  26. data/lib/deepl/requests/glossary/create.rb +18 -22
  27. data/lib/deepl/requests/glossary/destroy.rb +4 -16
  28. data/lib/deepl/requests/glossary/entries.rb +6 -14
  29. data/lib/deepl/requests/glossary/find.rb +3 -13
  30. data/lib/deepl/requests/glossary/language_pairs.rb +2 -2
  31. data/lib/deepl/requests/glossary/list.rb +2 -2
  32. data/lib/deepl/requests/languages.rb +6 -11
  33. data/lib/deepl/requests/languages_for_resource.rb +2 -0
  34. data/lib/deepl/requests/multilingual_glossary/create.rb +8 -0
  35. data/lib/deepl/requests/multilingual_glossary/destroy_dictionary.rb +4 -0
  36. data/lib/deepl/requests/multilingual_glossary/entries.rb +5 -3
  37. data/lib/deepl/requests/multilingual_glossary/helpers.rb +22 -14
  38. data/lib/deepl/requests/rephrase.rb +3 -1
  39. data/lib/deepl/requests/spoken_terms/create.rb +5 -0
  40. data/lib/deepl/requests/spoken_terms/destroy_term_list.rb +1 -0
  41. data/lib/deepl/requests/spoken_terms/entries.rb +1 -0
  42. data/lib/deepl/requests/spoken_terms/helpers.rb +9 -2
  43. data/lib/deepl/requests/style_profile/create.rb +5 -0
  44. data/lib/deepl/requests/style_profile/list.rb +2 -2
  45. data/lib/deepl/requests/style_rule/create.rb +25 -1
  46. data/lib/deepl/requests/style_rule/create_custom_instruction.rb +7 -0
  47. data/lib/deepl/requests/style_rule/helpers.rb +13 -4
  48. data/lib/deepl/requests/style_rule/list.rb +2 -0
  49. data/lib/deepl/requests/style_rule/update.rb +1 -0
  50. data/lib/deepl/requests/style_rule/update_custom_instruction.rb +2 -0
  51. data/lib/deepl/requests/translate.rb +20 -36
  52. data/lib/deepl/requests/translation_memory/create_export.rb +6 -1
  53. data/lib/deepl/requests/translation_memory/create_import.rb +10 -0
  54. data/lib/deepl/requests/translation_memory/download_export.rb +0 -4
  55. data/lib/deepl/requests/translation_memory/list.rb +2 -2
  56. data/lib/deepl/requests/translation_memory/segments.rb +2 -2
  57. data/lib/deepl/requests/translation_memory/storage_base.rb +5 -9
  58. data/lib/deepl/requests/write_improvements.rb +7 -0
  59. data/lib/deepl/resources/document_handle.rb +1 -26
  60. data/lib/deepl/resources/document_translation_status.rb +0 -12
  61. data/lib/deepl/resources/language.rb +4 -10
  62. data/lib/deepl/resources/multilingual_glossary.rb +4 -4
  63. data/lib/deepl/resources/style_rule.rb +1 -23
  64. data/lib/deepl/resources/translation_memory_job.rb +3 -4
  65. data/lib/deepl/resources/usage.rb +5 -38
  66. data/lib/deepl/utils/client_builder.rb +44 -9
  67. data/lib/deepl/utils/glossary_entries.rb +30 -0
  68. data/lib/deepl/utils/http_client_builder.rb +50 -13
  69. data/lib/deepl/utils/output_path.rb +25 -0
  70. data/lib/deepl/utils/term_validator.rb +3 -3
  71. data/lib/deepl/utils/translation_memory_operations.rb +230 -0
  72. data/lib/deepl.rb +6 -171
  73. data/lib/http_client_options.rb +2 -2
  74. data/lib/version.rb +1 -1
  75. data/upgrading_to_v4.md +374 -0
  76. metadata +9 -50
  77. data/.gitlab-ci.yml +0 -197
  78. data/lib/deepl/deprecation.rb +0 -42
  79. data/lib/deepl/document_api.rb +0 -150
  80. data/lib/deepl/exceptions/not_supported.rb +0 -20
  81. data/lib/deepl/glossary_api.rb +0 -38
  82. data/lib/deepl/style_rule_api.rb +0 -72
  83. data/lib/deepl/translation_memory_api.rb +0 -389
  84. data/license_checker.sh +0 -8
  85. data/spec/fixtures.rb +0 -33
  86. data/spec/offline/admin_client_spec.rb +0 -551
  87. data/spec/offline/client_spec.rb +0 -273
  88. data/spec/offline/configuration_spec.rb +0 -164
  89. data/spec/offline/constants_spec.rb +0 -180
  90. data/spec/offline/correct_text_spec.rb +0 -50
  91. data/spec/offline/deprecation_spec.rb +0 -32
  92. data/spec/offline/errors_spec.rb +0 -92
  93. data/spec/offline/glossaries_spec.rb +0 -98
  94. data/spec/offline/http_client_spec.rb +0 -319
  95. data/spec/offline/languages_spec.rb +0 -155
  96. data/spec/offline/module_methods_spec.rb +0 -13
  97. data/spec/offline/multilingual_glossaries_spec.rb +0 -358
  98. data/spec/offline/offline_helper.rb +0 -71
  99. data/spec/offline/rephrase_text_spec.rb +0 -73
  100. data/spec/offline/spoken_terms_spec.rb +0 -215
  101. data/spec/offline/style_profiles_spec.rb +0 -266
  102. data/spec/offline/style_rules_spec.rb +0 -318
  103. data/spec/offline/translate_document_spec.rb +0 -606
  104. data/spec/offline/translate_text_spec.rb +0 -286
  105. data/spec/offline/translation_memories_client_spec.rb +0 -256
  106. data/spec/offline/translation_memories_spec.rb +0 -463
  107. data/spec/offline/usage_spec.rb +0 -151
  108. data/spec/real_api/admin_client_spec.rb +0 -77
  109. data/spec/real_api/correct_text_spec.rb +0 -20
  110. data/spec/real_api/glossaries_spec.rb +0 -28
  111. data/spec/real_api/languages_spec.rb +0 -27
  112. data/spec/real_api/multilingual_glossaries_spec.rb +0 -53
  113. data/spec/real_api/proxy_spec.rb +0 -41
  114. data/spec/real_api/real_api_helper.rb +0 -65
  115. data/spec/real_api/rephrase_text_spec.rb +0 -16
  116. data/spec/real_api/spoken_terms_spec.rb +0 -56
  117. data/spec/real_api/style_profiles_spec.rb +0 -46
  118. data/spec/real_api/style_rules_spec.rb +0 -46
  119. data/spec/real_api/translate_document_spec.rb +0 -18
  120. data/spec/real_api/translate_text_spec.rb +0 -16
  121. data/spec/real_api/translation_memories_spec.rb +0 -56
  122. data/spec/real_api/usage_spec.rb +0 -20
  123. data/spec/spec_helper.rb +0 -13
@@ -12,8 +12,10 @@ module DeepL
12
12
  def initialize(api, style_id, label, prompt, source_language = nil, options = {})
13
13
  super(api, options)
14
14
  @style_id = style_rule_id(style_id)
15
+ check_non_empty!(label: label, prompt: prompt)
15
16
  @label = label
16
17
  @prompt = prompt
18
+ validate_language!('source_language', source_language, optional: true)
17
19
  @source_language = source_language
18
20
  end
19
21
 
@@ -29,6 +31,11 @@ module DeepL
29
31
 
30
32
  private
31
33
 
34
+ # A repeated creation request could create a second resource.
35
+ def retry_only_unprocessed?
36
+ true
37
+ end
38
+
32
39
  def build_custom_instruction(_request, response)
33
40
  data = JSON.parse(response.body)
34
41
  DeepL::Resources::CustomInstruction.new(data)
@@ -12,15 +12,24 @@ module DeepL
12
12
  private
13
13
 
14
14
  def style_rule_id(style_rule)
15
- return style_rule.style_id if style_rule.is_a?(DeepL::Resources::StyleRule)
15
+ id = style_rule.is_a?(DeepL::Resources::StyleRule) ? style_rule.style_id : style_rule
16
+ raise ArgumentError, 'Style rule ID must not be empty' if id.to_s.empty?
16
17
 
17
- style_rule
18
+ id
18
19
  end
19
20
 
20
21
  def custom_instruction_id(instruction)
21
- return instruction.id if instruction.is_a?(DeepL::Resources::CustomInstruction)
22
+ id = instruction.is_a?(DeepL::Resources::CustomInstruction) ? instruction.id : instruction
23
+ raise ArgumentError, 'Custom instruction ID must not be empty' if id.to_s.empty?
22
24
 
23
- instruction
25
+ id
26
+ end
27
+
28
+ # Raises ArgumentError for each of +values+ (name => value) that is nil or empty.
29
+ def check_non_empty!(values)
30
+ values.each do |name, value|
31
+ raise ArgumentError, "`#{name}` must not be empty" if value.to_s.empty?
32
+ end
24
33
  end
25
34
 
26
35
  # The path of a style rule list, with its ID and the custom instruction ID URL-encoded.
@@ -7,6 +7,8 @@ module DeepL
7
7
  module Requests
8
8
  module StyleRule
9
9
  class List < Base
10
+ accepts_options :page, :page_size, :detailed
11
+
10
12
  def initialize(api, options = {})
11
13
  super
12
14
  end
@@ -12,6 +12,7 @@ module DeepL
12
12
  def initialize(api, style_id, name, options = {})
13
13
  super(api, options)
14
14
  @style_id = style_rule_id(style_id)
15
+ check_non_empty!(name: name)
15
16
  @name = name
16
17
  end
17
18
 
@@ -14,8 +14,10 @@ module DeepL
14
14
  super(api, options)
15
15
  @style_id = style_rule_id(style_id)
16
16
  @instruction_id = custom_instruction_id(instruction_id)
17
+ check_non_empty!(label: label, prompt: prompt)
17
18
  @label = label
18
19
  @prompt = prompt
20
+ validate_language!('source_language', source_language, optional: true)
19
21
  @source_language = source_language
20
22
  end
21
23
 
@@ -5,7 +5,7 @@
5
5
 
6
6
  module DeepL
7
7
  module Requests
8
- class Translate < Base # rubocop:disable Metrics/ClassLength
8
+ class Translate < Base
9
9
  STRING_TO_BOOLEAN_MAP = { '1' => true, '0' => false }.freeze
10
10
  BOOLEAN_TO_STRING_MAP = { true => '1', false => '0' }.freeze
11
11
  STRING_TO_BOOLEAN_CONVERSION = ->(value) { STRING_TO_BOOLEAN_MAP[value] }
@@ -31,15 +31,23 @@ module DeepL
31
31
  custom_instructions: STRING_TO_SINGLE_ELEMENT_ARRAY_CONVERSION
32
32
  }.freeze
33
33
 
34
+ accepts_options :glossary, :glossary_ids, :style_rule, :style_profile, :translation_memory,
35
+ :translation_memory_threshold, :formality, :split_sentences,
36
+ :preserve_formatting, :context, :tag_handling, :tag_handling_version,
37
+ :outline_detection, :splitting_tags, :non_splitting_tags, :ignore_tags,
38
+ :model_type, :custom_instructions
39
+
34
40
  attr_reader :text, :source_lang, :target_lang, :ignore_tags, :splitting_tags,
35
41
  :non_splitting_tags, :model_type, :custom_instructions, :tag_handling_version
36
42
 
37
43
  def initialize(api, text, source_lang, target_lang, options = {}, additional_headers = {})
38
- # Options set to nil are unset and not sent.
39
- super(api, options.compact, additional_headers)
44
+ super(api, options, additional_headers)
40
45
  @text = text
41
46
  @source_lang = source_lang
42
47
  @target_lang = target_lang
48
+ validate_text!(text)
49
+ validate_languages!(source_lang, target_lang)
50
+ validate_translation_memory_threshold!
43
51
 
44
52
  tweak_parameters!
45
53
  end
@@ -49,38 +57,14 @@ module DeepL
49
57
  payload = { text: text_arrayified, target_lang: target_lang, show_billed_characters: true }
50
58
  payload[:source_lang] = source_lang unless source_lang.nil?
51
59
 
52
- if option?(:style_rule)
53
- style_rule = delete_option(:style_rule)
54
- unless style_rule.nil?
55
- payload[:style_id] = if style_rule.is_a?(DeepL::Resources::StyleRule)
56
- style_rule.style_id
57
- else
58
- style_rule.to_s
59
- end
60
- end
61
- end
62
-
63
- if option?(:style_profile)
64
- profile = delete_option(:style_profile)
65
- unless profile.nil?
66
- payload[:style_profile_id] = if profile.is_a?(DeepL::Resources::StyleProfile)
67
- profile.style_profile_id
68
- else
69
- profile.to_s
70
- end
71
- end
72
- end
73
-
74
- if option?(:translation_memory)
75
- tm = delete_option(:translation_memory)
76
- unless tm.nil?
77
- payload[:translation_memory_id] = if tm.is_a?(DeepL::Resources::TranslationMemory)
78
- tm.translation_memory_id
79
- else
80
- tm.to_s
81
- end
82
- end
83
- end
60
+ style_id = take_resource_option(:style_rule, [DeepL::Resources::StyleRule], :style_id)
61
+ payload[:style_id] = style_id unless style_id.nil?
62
+ profile_id = take_resource_option(:style_profile, [DeepL::Resources::StyleProfile],
63
+ :style_profile_id)
64
+ payload[:style_profile_id] = profile_id unless profile_id.nil?
65
+ tm_id = take_resource_option(:translation_memory, [DeepL::Resources::TranslationMemory],
66
+ :translation_memory_id)
67
+ payload[:translation_memory_id] = tm_id unless tm_id.nil?
84
68
 
85
69
  if option?(:translation_memory_threshold)
86
70
  threshold = delete_option(:translation_memory_threshold)
@@ -126,7 +110,7 @@ module DeepL
126
110
  )
127
111
  end
128
112
 
129
- texts.size == 1 ? texts.first : texts
113
+ text.is_a?(Array) ? texts : texts.first
130
114
  end
131
115
 
132
116
  def optional_string(value)
@@ -15,7 +15,7 @@ module DeepL
15
15
  end
16
16
 
17
17
  def request
18
- build_translation_memory_export(*execute_request_with_retries(post_request({})))
18
+ build_translation_memory_export(*execute_request_with_retries(bodiless_post_request))
19
19
  end
20
20
 
21
21
  def to_s
@@ -24,6 +24,11 @@ module DeepL
24
24
 
25
25
  private
26
26
 
27
+ # A repeated creation request could create a second resource.
28
+ def retry_only_unprocessed?
29
+ true
30
+ end
31
+
27
32
  def build_translation_memory_export(request, response)
28
33
  data = JSON.parse(response.body)
29
34
  # The API answers 200 when it reused a previously completed export, and 202 when it
@@ -7,10 +7,15 @@ module DeepL
7
7
  module Requests
8
8
  module TranslationMemory
9
9
  class CreateImport < Base
10
+ accepts_options :content_type, :display_name
11
+
10
12
  attr_reader :file_name, :content_length
11
13
 
12
14
  def initialize(api, file_name, content_length, options = {}, additional_headers = {})
13
15
  super(api, options, additional_headers)
16
+ raise ArgumentError, '`file_name` must not be empty' if file_name.to_s.empty?
17
+ raise ArgumentError, '`content_length` must be positive' unless content_length.positive?
18
+
14
19
  @file_name = file_name
15
20
  @content_length = content_length
16
21
  @content_type = delete_option(:content_type)
@@ -31,6 +36,11 @@ module DeepL
31
36
 
32
37
  private
33
38
 
39
+ # A repeated creation request could create a second resource.
40
+ def retry_only_unprocessed?
41
+ true
42
+ end
43
+
34
44
  def payload
35
45
  source_file = { file_name: file_name, content_length: content_length }
36
46
  source_file[:content_type] = @content_type if @content_type
@@ -28,10 +28,6 @@ module DeepL
28
28
 
29
29
  def extract_file(_request, response)
30
30
  File.binwrite(@output_file, response.body)
31
- rescue SystemCallError, IOError => e
32
- raise e unless api.client?
33
-
34
- raise Exceptions::Error, "Could not write the export to #{@output_file}: #{e.message}"
35
31
  end
36
32
  end
37
33
  end
@@ -7,7 +7,7 @@ module DeepL
7
7
  module Requests
8
8
  module TranslationMemory
9
9
  class List < Base
10
- SUPPORTED_OPTIONS = %w[page page_size].freeze
10
+ accepts_options :page, :page_size
11
11
 
12
12
  def initialize(api, options = {})
13
13
  super
@@ -31,7 +31,7 @@ module DeepL
31
31
  end
32
32
 
33
33
  def query_params
34
- SUPPORTED_OPTIONS.each_with_object({}) do |option_name, params|
34
+ self.class.accepted_options.each_with_object({}) do |option_name, params|
35
35
  value = option(option_name)
36
36
  params[option_name] = value.to_s unless value.nil?
37
37
  end
@@ -7,7 +7,7 @@ module DeepL
7
7
  module Requests
8
8
  module TranslationMemory
9
9
  class Segments < Base
10
- SUPPORTED_OPTIONS = %w[page_size page_cursor filter_text filter_case_sensitive].freeze
10
+ accepts_options :page_size, :page_cursor, :filter_text, :filter_case_sensitive
11
11
 
12
12
  attr_reader :translation_memory_id
13
13
 
@@ -32,7 +32,7 @@ module DeepL
32
32
  end
33
33
 
34
34
  def query_params
35
- SUPPORTED_OPTIONS.each_with_object({}) do |option_name, params|
35
+ self.class.accepted_options.each_with_object({}) do |option_name, params|
36
36
  value = option(option_name)
37
37
  params[option_name] = value.to_s unless value.nil?
38
38
  end
@@ -11,9 +11,8 @@ module DeepL
11
11
  # as a translation memory upload or download URL. Those URLs point outside of the DeepL
12
12
  # API, so they are requested over their own connection and send only the User-Agent: neither
13
13
  # the DeepL `Authorization` header nor other caller headers. That connection uses the same
14
- # proxy, SSL and timeout options as the API connection. A non-2xx response raises the API
15
- # error class for its status (e.g. DeepL::Exceptions::AuthorizationFailed for 401/403) in the
16
- # module-level API and a plain DeepL::Exceptions::Error in DeepL::Client.
14
+ # proxy, SSL and timeout options as the API connection. A non-2xx response raises a plain
15
+ # DeepL::Exceptions::Error.
17
16
 
18
17
  class StorageBase < DeepL::Requests::Base
19
18
  attr_reader :storage_url
@@ -21,7 +20,7 @@ module DeepL
21
20
  def initialize(api, storage_url, options = {}, additional_headers = {})
22
21
  super(api, options, additional_headers)
23
22
  if storage_url.nil? || storage_url.empty?
24
- raise Exceptions::Error, 'Storage URL must not be empty'
23
+ raise ArgumentError, 'Storage URL must not be empty'
25
24
  end
26
25
 
27
26
  @storage_url = storage_url
@@ -52,12 +51,9 @@ module DeepL
52
51
  end
53
52
 
54
53
  # Storage responses are not DeepL API responses, so their statuses carry none of the API's
55
- # meanings: an expired URL replies 403, which is no authorization failure. DeepL::Client
56
- # raises a plain error; until the next major version, the module-level API raises the API
57
- # error classes it has released.
58
- def validate_response!(response, request = nil)
54
+ # meanings: an expired URL replies 403, which is no authorization failure.
55
+ def validate_response!(response, _request = nil)
59
56
  return if response.is_a?(Net::HTTPSuccess)
60
- raise Utils::ExceptionBuilder.new(response, request).build unless api.client?
61
57
 
62
58
  status = response.code.to_i
63
59
  raise Exceptions::Error.new(
@@ -10,6 +10,13 @@ module DeepL
10
10
  module WriteImprovements
11
11
  private
12
12
 
13
+ # +nil+ keeps the language of the text; an empty target language is rejected.
14
+ def validate_optional_target_lang!(target_lang)
15
+ return if target_lang.nil? || !target_lang.to_s.empty?
16
+
17
+ raise ArgumentError, '`target_lang` must not be empty; pass nil to keep the language'
18
+ end
19
+
13
20
  # Returns one DeepL::Resources::Text per improvement. Raises DeepL::Exceptions::Error if
14
21
  # the response has fewer improvements than +input_count+ input texts.
15
22
  def build_improvements(input_count, request, response)
@@ -8,7 +8,7 @@ module DeepL
8
8
  class DocumentHandle < Base
9
9
  attr_reader :document_id, :document_key
10
10
 
11
- # +api+ is the connection the handle was created with; status queries go through it.
11
+ # The +api:+ keyword is kept for compatibility and not used.
12
12
  # A handle for a stored ID and key needs only those two: +DocumentHandle.new(id, key)+.
13
13
  def initialize(document_id, document_key, request = nil, response = nil, api: nil)
14
14
  super(request, response)
@@ -26,31 +26,6 @@ module DeepL
26
26
  def inspect
27
27
  "#<#{self.class.name} document_id=#{document_id.inspect}>"
28
28
  end
29
-
30
- ##
31
- # For this DocumentHandle, waits until the document translation is finished (done or
32
- # failed) and returns the final status of the document. Stops early only if the
33
- # deprecated +max_doc_status_queries+ is configured.
34
- #
35
- # @deprecated Use DeepL::Client#translate_document_wait_until_done instead.
36
- # @return [DeepL::Resources::DocumentTranslationStatus] Final status of the document
37
- # translation.
38
- def wait_until_document_translation_finished
39
- Deprecation.warn_once('DocumentHandle#wait_until_document_translation_finished',
40
- '[DEPRECATION] DeepL::Resources::DocumentHandle#' \
41
- 'wait_until_document_translation_finished is deprecated, use ' \
42
- 'DeepL::Client#translate_document_wait_until_done instead.')
43
- Utils::DocumentPoller.wait_until_finished(
44
- api, self, max_queries: api.configuration.max_doc_status_queries
45
- )
46
- end
47
-
48
- private
49
-
50
- # Handles created without a connection fall back to the deprecated module configuration.
51
- def api
52
- @api || DeepL.send(:module_api)
53
- end
54
29
  end
55
30
  end
56
31
  end
@@ -31,18 +31,6 @@ module DeepL
31
31
  status == Constants::DocumentStatusCode::DONE
32
32
  end
33
33
 
34
- ##
35
- # Checks if the translation finished successfully
36
- #
37
- # @deprecated Use #done? instead.
38
- # @return [true] if so
39
- def successful?
40
- Deprecation.warn_once('DeepL::Resources::DocumentTranslationStatus#successful?',
41
- '[DEPRECATION] DeepL::Resources::DocumentTranslationStatus#' \
42
- 'successful? is deprecated, use #done? instead.')
43
- done?
44
- end
45
-
46
34
  ##
47
35
  # Checks if there was an error during translation
48
36
  #
@@ -8,14 +8,12 @@ module DeepL
8
8
  class Language < Base
9
9
  attr_reader :code, :name
10
10
 
11
- # +client:+ is true for a language returned by DeepL::Client. @api private
12
- def initialize(code, name, supports_formality, *args, client: false)
11
+ def initialize(code, name, supports_formality, *args)
13
12
  super(*args)
14
13
 
15
14
  @code = code
16
15
  @name = name
17
16
  @supports_formality = supports_formality
18
- @client = client
19
17
  end
20
18
 
21
19
  def to_s
@@ -24,14 +22,10 @@ module DeepL
24
22
 
25
23
  # Whether the target language supports the +formality+ option.
26
24
  #
27
- # @return [Boolean, nil] +true+ or +false+ for a target language; for a source language
28
- # +nil+ if it came from DeepL::Client.
29
- # @raise [DeepL::Exceptions::NotSupported] For a source language from the module-level
30
- # +DeepL.languages+, until the next major version.
25
+ # @return [Boolean, nil] +true+ or +false+ for a target language, +nil+ for a source
26
+ # language.
31
27
  def supports_formality?
32
- return @supports_formality unless @supports_formality.nil? && !@client
33
-
34
- raise Exceptions::NotSupported, 'Support formality is only available on target languages'
28
+ @supports_formality
35
29
  end
36
30
  end
37
31
  end
@@ -36,8 +36,8 @@ module DeepL
36
36
  # @param [Hash{String => String}, Array<Array(String, String)>, String] entries The target
37
37
  # term of each source term, as a hash, source/target pairs or a TSV string; terms are
38
38
  # stripped and checked when sent.
39
- # @raise [DeepL::Exceptions::ValidationError] If a pair or TSV line is not exactly two
40
- # terms, or a source term appears twice.
39
+ # @raise [DeepL::Exceptions::ValidationError] (an ArgumentError) If a pair or TSV line is not
40
+ # exactly two terms, or a source term appears twice.
41
41
  def initialize(source_lang, target_lang, entries, request = nil, response = nil)
42
42
  super(request, response)
43
43
 
@@ -58,12 +58,12 @@ module DeepL
58
58
  end
59
59
 
60
60
  # @api private
61
- # Raises ValidationError unless each pair is two strings and no source term, stripped as
61
+ # Raises ValidationError unless each pair is two terms and no source term, stripped as
62
62
  # the term check strips it, appears twice. Returns +pairs+.
63
63
  def self.check_pairs!(pairs)
64
64
  seen = {}
65
65
  pairs.each do |pair|
66
- unless pair.is_a?(Array) && pair.size == 2 && pair.all?(String)
66
+ unless pair.size == 2
67
67
  raise Exceptions::ValidationError, "Entry #{pair.inspect} must be two terms"
68
68
  end
69
69
 
@@ -7,27 +7,6 @@ require 'time'
7
7
 
8
8
  module DeepL
9
9
  module Resources
10
- class ConfiguredRules
11
- attr_reader :dates_and_times, :formatting, :numbers, :punctuation,
12
- :spelling_and_grammar, :style_and_tone, :vocabulary
13
-
14
- def initialize(configured_rules_data)
15
- @dates_and_times = extract_rule(configured_rules_data, 'dates_and_times')
16
- @formatting = extract_rule(configured_rules_data, 'formatting')
17
- @numbers = extract_rule(configured_rules_data, 'numbers')
18
- @punctuation = extract_rule(configured_rules_data, 'punctuation')
19
- @spelling_and_grammar = extract_rule(configured_rules_data, 'spelling_and_grammar')
20
- @style_and_tone = extract_rule(configured_rules_data, 'style_and_tone')
21
- @vocabulary = extract_rule(configured_rules_data, 'vocabulary')
22
- end
23
-
24
- private
25
-
26
- def extract_rule(data, key)
27
- data[key] || {}
28
- end
29
- end
30
-
31
10
  class CustomInstruction
32
11
  attr_reader :id, :label, :prompt, :source_language
33
12
 
@@ -62,8 +41,7 @@ module DeepL
62
41
  end
63
42
 
64
43
  def extract_configured_rules(style_rule)
65
- configured_rules_data = style_rule['configured_rules']
66
- @configured_rules = configured_rules_data ? ConfiguredRules.new(configured_rules_data) : nil
44
+ @configured_rules = style_rule['configured_rules']
67
45
  end
68
46
 
69
47
  def extract_custom_instructions(style_rule)
@@ -12,7 +12,6 @@ module DeepL
12
12
  STATUS_AWAITING_INPUT = 'awaiting_input'
13
13
  STATUS_PROCESSING = 'processing'
14
14
  STATUS_COMPLETED = 'completed'
15
- STATUS_DOWNLOADED = 'downloaded'
16
15
  STATUS_FAILED = 'failed'
17
16
  STATUS_EXPIRED = 'expired'
18
17
 
@@ -33,13 +32,13 @@ module DeepL
33
32
  end
34
33
 
35
34
  ##
36
- # Checks if the job terminated. Note that this could be due to an error as well, but means
37
- # no further waiting is necessary.
35
+ # Checks if the job terminated: its status is +completed+, +failed+ or +expired+. Note that
36
+ # this could be due to an error as well, but means no further waiting is necessary.
38
37
  #
39
38
  # @return [true] if so
40
39
 
41
40
  def finished?
42
- [STATUS_COMPLETED, STATUS_DOWNLOADED, STATUS_FAILED, STATUS_EXPIRED].include?(status)
41
+ [STATUS_COMPLETED, STATUS_FAILED, STATUS_EXPIRED].include?(status)
43
42
  end
44
43
 
45
44
  ##
@@ -25,8 +25,7 @@ module DeepL
25
25
  end
26
26
  end
27
27
 
28
- DETAIL_TYPES = %i[document team_document api_key_character speech_to_text_minutes
29
- speech_to_speech_minutes].freeze
28
+ DETAIL_TYPES = %i[api_key_character speech_to_text_minutes speech_to_speech_minutes].freeze
30
29
  KEYWORD_FIELDS = (DETAIL_TYPES + %i[products start_time end_time]).freeze
31
30
 
32
31
  attr_reader :character, *KEYWORD_FIELDS
@@ -34,8 +33,6 @@ module DeepL
34
33
  ##
35
34
  # Each keyword argument is nil when the response does not contain the field.
36
35
  #
37
- # @param [Detail, nil] document Document usage, for accounts with a document limit.
38
- # @param [Detail, nil] team_document Document usage of the whole team.
39
36
  # @param [Detail, nil] api_key_character Character usage of this API key (API Pro).
40
37
  # @param [Detail, nil] speech_to_text_minutes Speech-to-text usage in minutes (API Pro).
41
38
  # @param [Detail, nil] speech_to_speech_minutes Speech-to-speech usage in minutes (API Pro).
@@ -56,45 +53,15 @@ module DeepL
56
53
  KEYWORD_FIELDS.each { |field| instance_variable_set("@#{field}", fields[field]) }
57
54
  end
58
55
 
59
- ##
60
- # @deprecated Use +character.count+ instead.
61
- def character_count
62
- deprecated(:character_count, 'character.count')
63
- @character_count
64
- end
65
-
66
- ##
67
- # @deprecated Use +character.limit+ instead.
68
- def character_limit
69
- deprecated(:character_limit, 'character.limit')
70
- @character_limit
71
- end
72
-
73
56
  def to_s
74
57
  "#{@character_count} / #{@character_limit}"
75
58
  end
76
59
 
77
60
  ##
78
- # @deprecated Use +character.limit_reached?+ or +any_limit_reached?+ instead.
79
- def quota_exceeded?
80
- deprecated(:quota_exceeded?, 'character.limit_reached? or any_limit_reached?')
81
- @character_count >= @character_limit
82
- end
83
-
84
- ##
85
- # True if the character, document or team document limit has been reached. The API Pro
86
- # usage types (api_key_character and the speech minutes) are not considered; call
87
- # limit_reached? on them directly.
88
- def any_limit_reached?
89
- [character, document, team_document].compact.any?(&:limit_reached?)
90
- end
91
-
92
- private
93
-
94
- def deprecated(name, replacement)
95
- Deprecation.warn_once("DeepL::Resources::Usage##{name}",
96
- "[DEPRECATION] DeepL::Resources::Usage##{name} is deprecated, " \
97
- "use #{replacement} instead.", uplevel: 3)
61
+ # True if the account's character limit or this API key's character limit is reached; the
62
+ # speech minutes have their own details. A missing detail counts as not reached.
63
+ def any_character_limit_reached?
64
+ [character, api_key_character].compact.any?(&:limit_reached?)
98
65
  end
99
66
  end
100
67
 
@@ -12,31 +12,66 @@ module DeepL
12
12
  extend self
13
13
 
14
14
  def build_api(key, key_name:, server_url:, default_server_url:, headers:, max_retries:,
15
- timeout:, proxy:, send_platform_info:, app_info:, http_client_options:, logger:) # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/ParameterLists
15
+ timeout:, proxy:, send_platform_info:, app_info:, http_client_options:, logger:) # rubocop:disable Metrics/AbcSize,Metrics/MethodLength,Metrics/ParameterLists
16
16
  key = key.to_s.strip
17
17
  raise ArgumentError, "#{key_name} must not be empty" if key.empty?
18
18
 
19
+ host = host(server_url, default_server_url)
19
20
  headers = (headers || {}).to_h
20
- app_info = AppInfo.from(app_info)
21
21
  configuration = Configuration.new(
22
- { auth_key: key, host: server_url || default_server_url,
23
- max_network_retries: max_retries, timeout: timeout, logger: logger,
24
- headers: headers.reject { |name, _| user_agent_header?(name) },
25
- user_agent: headers.find { |name, _| user_agent_header?(name) }&.last },
26
- app_info&.app_name, app_info&.app_version, send_platform_info
22
+ auth_key: key, host: host, max_network_retries: or_default(max_retries, 5),
23
+ timeout: or_default(timeout, 10), logger: logger,
24
+ headers: headers.reject { |name, _| user_agent_header?(name) },
25
+ user_agent: headers.find { |name, _| user_agent_header?(name) }&.last,
26
+ send_platform_info: or_default(send_platform_info, true), app_info: AppInfo.from(app_info)
27
27
  )
28
- API.new(configuration, merge_proxy(http_client_options, proxy), client: true)
28
+ API.new(configuration, merge_proxy(http_client_options, proxy))
29
29
  end
30
30
 
31
31
  private
32
32
 
33
+ # nil means the option was not given, so it takes the constructor default.
34
+ def or_default(value, default)
35
+ value.nil? ? default : value
36
+ end
37
+
38
+ # Validates the server URL and removes its trailing slashes: requests append /v2/... or
39
+ # /v3/... to the host, so a trailing slash would give //v2/...
40
+ def host(server_url, default_server_url)
41
+ return default_server_url if server_url.nil?
42
+
43
+ validate_server_url!(server_url)
44
+ server_url.to_s.sub(%r{/+\z}, '')
45
+ end
46
+
47
+ # The server URL must be an absolute http or https URL with a host; a port and a path
48
+ # prefix are allowed. +nil+ selects the default server.
49
+ def validate_server_url!(server_url)
50
+ return if server_url.nil?
51
+
52
+ uri = begin
53
+ URI.parse(server_url.to_s)
54
+ rescue URI::InvalidURIError
55
+ nil
56
+ end
57
+ return if uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
58
+
59
+ # The URL is left out of the message: it can contain credentials.
60
+ raise ArgumentError, 'server_url must be an absolute http or https URL with a host',
61
+ cause: nil
62
+ end
63
+
33
64
  def user_agent_header?(name)
34
65
  name.to_s.casecmp?('user-agent')
35
66
  end
36
67
 
68
+ def no_proxy?(proxy)
69
+ proxy.nil? || (proxy.respond_to?(:empty?) && proxy.empty?)
70
+ end
71
+
37
72
  def merge_proxy(options, proxy) # rubocop:disable Metrics/MethodLength
38
73
  return options if proxy.nil?
39
- if options && !(options.proxy.nil? || options.proxy.empty?)
74
+ if options && !no_proxy?(options.proxy)
40
75
  raise ArgumentError,
41
76
  'Set the proxy either with proxy: or in http_client_options:, not both'
42
77
  end