deepl-rb 3.6.0 → 3.7.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 (131) hide show
  1. checksums.yaml +4 -4
  2. data/.circleci/config.yml +27 -0
  3. data/.github/workflows/add_issues_to_kanban.yml +16 -0
  4. data/.gitlab-ci.yml +177 -0
  5. data/.rubocop.yml +51 -0
  6. data/CHANGELOG.md +40 -3
  7. data/CODE_OF_CONDUCT.md +132 -0
  8. data/CONTRIBUTING.md +37 -0
  9. data/Gemfile +24 -0
  10. data/README.md +153 -22
  11. data/Rakefile +58 -0
  12. data/SECURITY.md +58 -0
  13. data/VERSION +1 -0
  14. data/deepl-rb.gemspec +167 -0
  15. data/lib/deepl/api.rb +22 -0
  16. data/lib/deepl/configuration.rb +59 -0
  17. data/lib/deepl/constants/base_constant.rb +18 -0
  18. data/lib/deepl/constants/formality.rb +16 -0
  19. data/lib/deepl/constants/model_type.rb +14 -0
  20. data/lib/deepl/constants/split_sentences.rb +14 -0
  21. data/lib/deepl/constants/tag_handling.rb +13 -0
  22. data/lib/deepl/constants/tone.rb +20 -0
  23. data/lib/deepl/constants/writing_style.rb +20 -0
  24. data/lib/deepl/document_api.rb +121 -0
  25. data/lib/deepl/exceptions/authorization_failed.rb +14 -0
  26. data/lib/deepl/exceptions/bad_request.rb +16 -0
  27. data/lib/deepl/exceptions/document_translation_error.rb +15 -0
  28. data/lib/deepl/exceptions/error.rb +14 -0
  29. data/lib/deepl/exceptions/limit_exceeded.rb +18 -0
  30. data/lib/deepl/exceptions/not_found.rb +16 -0
  31. data/lib/deepl/exceptions/not_supported.rb +14 -0
  32. data/lib/deepl/exceptions/quota_exceeded.rb +14 -0
  33. data/lib/deepl/exceptions/request_entity_too_large.rb +15 -0
  34. data/lib/deepl/exceptions/request_error.rb +21 -0
  35. data/lib/deepl/exceptions/server_error.rb +18 -0
  36. data/lib/deepl/glossary_api.rb +38 -0
  37. data/lib/deepl/requests/base.rb +212 -0
  38. data/lib/deepl/requests/document/download.rb +44 -0
  39. data/lib/deepl/requests/document/get_status.rb +44 -0
  40. data/lib/deepl/requests/document/upload.rb +75 -0
  41. data/lib/deepl/requests/glossary/create.rb +59 -0
  42. data/lib/deepl/requests/glossary/destroy.rb +37 -0
  43. data/lib/deepl/requests/glossary/entries.rb +37 -0
  44. data/lib/deepl/requests/glossary/find.rb +38 -0
  45. data/lib/deepl/requests/glossary/language_pairs.rb +38 -0
  46. data/lib/deepl/requests/glossary/list.rb +37 -0
  47. data/lib/deepl/requests/languages.rb +37 -0
  48. data/lib/deepl/requests/rephrase.rb +55 -0
  49. data/lib/deepl/requests/style_rule/create.rb +46 -0
  50. data/lib/deepl/requests/style_rule/create_custom_instruction.rb +45 -0
  51. data/lib/deepl/requests/style_rule/destroy.rb +39 -0
  52. data/lib/deepl/requests/style_rule/destroy_custom_instruction.rb +40 -0
  53. data/lib/deepl/requests/style_rule/find.rb +40 -0
  54. data/lib/deepl/requests/style_rule/find_custom_instruction.rb +41 -0
  55. data/lib/deepl/requests/style_rule/list.rb +59 -0
  56. data/lib/deepl/requests/style_rule/update.rb +42 -0
  57. data/lib/deepl/requests/style_rule/update_configured_rules.rb +41 -0
  58. data/lib/deepl/requests/style_rule/update_custom_instruction.rb +47 -0
  59. data/lib/deepl/requests/translate.rb +106 -0
  60. data/lib/deepl/requests/translation_memory/list.rb +58 -0
  61. data/lib/deepl/requests/usage.rb +33 -0
  62. data/lib/deepl/resources/base.rb +17 -0
  63. data/lib/deepl/resources/document_handle.rb +57 -0
  64. data/lib/deepl/resources/document_translation_status.rb +54 -0
  65. data/lib/deepl/resources/glossary.rb +28 -0
  66. data/lib/deepl/resources/language.rb +30 -0
  67. data/lib/deepl/resources/language_pair.rb +23 -0
  68. data/lib/deepl/resources/style_rule.rb +86 -0
  69. data/lib/deepl/resources/text.rb +24 -0
  70. data/lib/deepl/resources/translation_memory.rb +25 -0
  71. data/lib/deepl/resources/usage.rb +27 -0
  72. data/lib/deepl/style_rule_api.rb +61 -0
  73. data/lib/deepl/translation_memory_api.rb +17 -0
  74. data/lib/deepl/utils/backoff_timer.rb +46 -0
  75. data/lib/deepl/utils/exception_builder.rb +34 -0
  76. data/lib/deepl.rb +175 -0
  77. data/lib/http_client_options.rb +22 -0
  78. data/lib/version.rb +8 -0
  79. data/spec/api/api_spec.rb +20 -0
  80. data/spec/api/configuration_spec.rb +122 -0
  81. data/spec/api/deepl_spec.rb +460 -0
  82. data/spec/constants/constants_spec.rb +158 -0
  83. data/spec/fixtures/vcr_cassettes/deepl_document.yml +95 -0
  84. data/spec/fixtures/vcr_cassettes/deepl_document_download.yml +1214 -0
  85. data/spec/fixtures/vcr_cassettes/deepl_glossaries.yml +1163 -0
  86. data/spec/fixtures/vcr_cassettes/deepl_languages.yml +54 -0
  87. data/spec/fixtures/vcr_cassettes/deepl_rephrase.yml +87 -0
  88. data/spec/fixtures/vcr_cassettes/deepl_translate.yml +358 -0
  89. data/spec/fixtures/vcr_cassettes/deepl_usage.yml +129 -0
  90. data/spec/fixtures/vcr_cassettes/glossaries.yml +1702 -0
  91. data/spec/fixtures/vcr_cassettes/languages.yml +229 -0
  92. data/spec/fixtures/vcr_cassettes/rephrase_texts.yml +401 -0
  93. data/spec/fixtures/vcr_cassettes/style_rules.yml +92 -0
  94. data/spec/fixtures/vcr_cassettes/style_rules_crud.yml +926 -0
  95. data/spec/fixtures/vcr_cassettes/translate_texts.yml +10630 -0
  96. data/spec/fixtures/vcr_cassettes/translation_memories.yml +74 -0
  97. data/spec/fixtures/vcr_cassettes/usage.yml +171 -0
  98. data/spec/integration_tests/document_api_spec.rb +178 -0
  99. data/spec/integration_tests/integration_test_utils.rb +170 -0
  100. data/spec/integration_tests/style_rule_api_spec.rb +135 -0
  101. data/spec/integration_tests/translation_memory_api_spec.rb +70 -0
  102. data/spec/requests/extra_body_parameters_types_spec.rb +82 -0
  103. data/spec/requests/glossary/create_spec.rb +65 -0
  104. data/spec/requests/glossary/destroy_spec.rb +66 -0
  105. data/spec/requests/glossary/entries_spec.rb +62 -0
  106. data/spec/requests/glossary/find_spec.rb +68 -0
  107. data/spec/requests/glossary/language_pairs_spec.rb +40 -0
  108. data/spec/requests/glossary/list_spec.rb +54 -0
  109. data/spec/requests/languages_spec.rb +68 -0
  110. data/spec/requests/rephrase_spec.rb +172 -0
  111. data/spec/requests/style_rule/create_custom_instruction_spec.rb +54 -0
  112. data/spec/requests/style_rule/create_spec.rb +45 -0
  113. data/spec/requests/style_rule/destroy_custom_instruction_spec.rb +54 -0
  114. data/spec/requests/style_rule/destroy_spec.rb +54 -0
  115. data/spec/requests/style_rule/find_custom_instruction_spec.rb +56 -0
  116. data/spec/requests/style_rule/find_spec.rb +56 -0
  117. data/spec/requests/style_rule/list_spec.rb +58 -0
  118. data/spec/requests/style_rule/update_configured_rules_spec.rb +52 -0
  119. data/spec/requests/style_rule/update_custom_instruction_spec.rb +58 -0
  120. data/spec/requests/style_rule/update_spec.rb +48 -0
  121. data/spec/requests/translate_spec.rb +492 -0
  122. data/spec/requests/translation_memory/list_spec.rb +61 -0
  123. data/spec/requests/usage_spec.rb +43 -0
  124. data/spec/resources/glossary_spec.rb +38 -0
  125. data/spec/resources/language_pair_spec.rb +23 -0
  126. data/spec/resources/language_spec.rb +45 -0
  127. data/spec/resources/text_spec.rb +23 -0
  128. data/spec/resources/translation_memory_spec.rb +35 -0
  129. data/spec/resources/usage_spec.rb +35 -0
  130. data/spec/spec_helper.rb +92 -0
  131. metadata +130 -3
@@ -0,0 +1,20 @@
1
+ # Copyright 2025 DeepL SE (https://www.deepl.com)
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Constants
8
+ class Tone < BaseConstant
9
+ DEFAULT = 'default'
10
+ ENTHUSIASTIC = 'enthusiastic'
11
+ FRIENDLY = 'friendly'
12
+ CONFIDENT = 'confident'
13
+ DIPLOMATIC = 'diplomatic'
14
+ PREFER_ENTHUSIASTIC = 'prefer_enthusiastic'
15
+ PREFER_FRIENDLY = 'prefer_friendly'
16
+ PREFER_CONFIDENT = 'prefer_confident'
17
+ PREFER_DIPLOMATIC = 'prefer_diplomatic'
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,20 @@
1
+ # Copyright 2025 DeepL SE (https://www.deepl.com)
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Constants
8
+ class WritingStyle < BaseConstant
9
+ DEFAULT = 'default'
10
+ SIMPLE = 'simple'
11
+ BUSINESS = 'business'
12
+ ACADEMIC = 'academic'
13
+ CASUAL = 'casual'
14
+ PREFER_SIMPLE = 'prefer_simple'
15
+ PREFER_BUSINESS = 'prefer_business'
16
+ PREFER_ACADEMIC = 'prefer_academic'
17
+ PREFER_CASUAL = 'prefer_casual'
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,121 @@
1
+ # Copyright 2024 DeepL SE (https://www.deepl.com)
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ class DocumentApi
8
+ def initialize(api, options = {})
9
+ @api = api
10
+ @options = options
11
+ end
12
+
13
+ ##
14
+ # Uploads the file at the given +input_file_path+ to be translated from +source_lang+ into
15
+ # +target_lang+. The API interface is async, so you need to poll using the returned
16
+ # `DeepL::Resources::DocumentHandle` until the translation is finished, then you can download it
17
+ #
18
+ # @param [String] input_file_path File path to the file to be translated
19
+ # @param [String, nil] source_lang Source language to use for the translation. `nil` will cause
20
+ # automatic source langauge detection to be used. Must be
21
+ # formatted as ISO 639-1, 2-letter language codes.
22
+ # @param [String] target_lang Target language to use for the translation. Must be formatted as
23
+ # ISO 639-1, 2-letter language codes, plus a hyphen "-" with the
24
+ # variant identifier for languages with variants/dialects/... .
25
+ # @param [String, nil] filename The filename of the file, including its extension. Used to open
26
+ # the different kinds of documents (PDFs, etc). If nil, will use
27
+ # the filename of +input_file_path+.
28
+ # @param [Hash] options Additional (body) options for the upload.
29
+ # @param [Hash] additional_headers Additional HTTP headers for the upload.
30
+ # @return [DeepL::Resources::DocumentHandle] Document handle for the uploaded document.
31
+
32
+ def upload(input_file_path, source_lang, target_lang, filename = nil, options = {},
33
+ additional_headers = {})
34
+ DeepL::Requests::Document::Upload.new(@api, input_file_path, source_lang, target_lang,
35
+ filename, options, additional_headers)
36
+ .request
37
+ end
38
+
39
+ ##
40
+ # Queries the status of the translation of the document with the given +document_handle+.
41
+ #
42
+ # @param [DeepL::Resources::DocumentHandle] document_handle Handle returned by the `upload`
43
+ # method.
44
+ # @param [Hash] options Additional options for the upload.
45
+ # @param [Hash] additional_headers Additional HTTP headers for the status check.
46
+ # @return [DeepL::Resources::DocumentTranslationStatus] Status of the document translation.
47
+
48
+ def get_status(document_handle, options = {}, additional_headers = {})
49
+ DeepL::Requests::Document::GetStatus.new(@api, document_handle.document_id,
50
+ document_handle.document_key, options,
51
+ additional_headers).request
52
+ end
53
+
54
+ ##
55
+ # Downloads the document identified by the +document_handle+ to +output_file+
56
+ #
57
+ # @param [DeepL::Resources::DocumentHandle] document_handle Handle returned by the `upload`
58
+ # method.
59
+ # @param [String] output_file Path to the file to write to. Will be overwritten if the file
60
+ # already exists.
61
+ # @return [DeepL::Resources::DocumentTranslationStatus] Status of the document translation.
62
+
63
+ def download(document_handle, output_file)
64
+ DeepL::Requests::Document::Download.new(@api, document_handle.document_id,
65
+ document_handle.document_key, output_file).request
66
+ end
67
+
68
+ ##
69
+ # Translates a document with the DeepL API, `sleep`ing during waiting periods. Returns the
70
+ # status that was queried last. This can be either because the document translation terminated
71
+ # (successfully or with an error) or because the maximum number of status requests have been
72
+ # made. See the parameter `max_doc_status_queries` for details.
73
+ #
74
+ # @raise [DocumentTranslationError] If any error occurs during the process.
75
+ #
76
+ # @param [String] input_file Path to the file to be translated
77
+ # @param [String] output_file Path to the file to write to. Will be overwritten if the file
78
+ # already exists.
79
+ # @param [String, nil] source_lang Source language to use for the translation. `nil` will cause
80
+ # automatic source langauge detection to be used. Must be
81
+ # formatted as ISO 639-1, 2-letter language codes.
82
+ # @param [String] target_lang Target language to use for the translation. Must be formatted as
83
+ # ISO 639-1, 2-letter language codes, plus a hyphen "-" with the
84
+ # variant identifier for languages with variants/dialects/... .
85
+ # @param [String, nil] filename The filename of the file, including its extension. Used to open
86
+ # the different kinds of documents (PDFs, etc). If nil, will use
87
+ # the filename of +input_file_path+.
88
+ # @param [Hash] options Additional options for the upload.
89
+ # @param [Hash] additional_headers Additional headers for the upload.
90
+ # @return [DeepL::Resources::DocumentTranslationStatus] Status of the document translation.
91
+
92
+ def translate_document(input_file, output_file, source_lang, target_lang, # rubocop:disable Metrics/MethodLength,Metrics/ParameterLists
93
+ filename = nil, options = {}, additional_headers = {})
94
+ raise IOError 'File already exists at output path' if File.exist?(output_file)
95
+
96
+ begin
97
+ handle = upload(input_file, source_lang, target_lang, filename, options,
98
+ additional_headers)
99
+ translate_document_wait_and_download(handle, output_file)
100
+ rescue StandardError => e
101
+ FileUtils.rm_f(output_file)
102
+ raise Exceptions::DocumentTranslationError.new(
103
+ "Error occurred during document translation: #{e.message}", handle
104
+ )
105
+ end
106
+ end
107
+
108
+ private
109
+
110
+ def translate_document_wait_and_download(document_handle, output_file)
111
+ doc_status = document_handle.wait_until_document_translation_finished
112
+ if doc_status.error?
113
+ raise Exceptions::DocumentTranslationError.new(
114
+ "Exception when querying document status #{doc_status.error_message}", document_handle
115
+ )
116
+ else
117
+ download(document_handle, output_file)
118
+ end
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,14 @@
1
+ # Copyright 2018 Daniel Herzog
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Exceptions
8
+ class AuthorizationFailed < RequestError
9
+ def to_s
10
+ 'Authorization failed. Please supply a valid auth_key parameter.'
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,16 @@
1
+ # Copyright 2018 Daniel Herzog
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Exceptions
8
+ class BadRequest < RequestError
9
+ def to_s
10
+ JSON.parse(response.body)['message']
11
+ rescue JSON::ParserError
12
+ response.body
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,15 @@
1
+ # Copyright 2024 DeepL SE (https://www.deepl.com)
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Exceptions
8
+ class DocumentTranslationError < Error
9
+ def initialize(message, handle)
10
+ super(message)
11
+ @handle = handle
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,14 @@
1
+ # Copyright 2018 Daniel Herzog
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Exceptions
8
+ class Error < StandardError
9
+ def should_retry?
10
+ false
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,18 @@
1
+ # Copyright 2018 Daniel Herzog
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Exceptions
8
+ class LimitExceeded < RequestError
9
+ def to_s
10
+ 'Limit exceeded. Please wait and send your request once again.'
11
+ end
12
+
13
+ def should_retry?
14
+ true
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,16 @@
1
+ # Copyright 2022 Daniel Herzog
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Exceptions
8
+ class NotFound < RequestError
9
+ def to_s
10
+ JSON.parse(response.body)['message']
11
+ rescue JSON::ParserError
12
+ response.body
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,14 @@
1
+ # Copyright 2022 Daniel Herzog
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Exceptions
8
+ class NotSupported < Error
9
+ def initialize(msg = 'The feature is not supported')
10
+ super
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,14 @@
1
+ # Copyright 2018 Daniel Herzog
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Exceptions
8
+ class QuotaExceeded < RequestError
9
+ def to_s
10
+ 'Quota exceeded. The character limit has been reached.'
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,15 @@
1
+ # Copyright 2022 Daniel Herzog
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Exceptions
8
+ class RequestEntityTooLarge < RequestError
9
+ def to_s
10
+ 'The request size has reached the supported limit. ' \
11
+ "Make sure that you're not sending more than 50 text parts."
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,21 @@
1
+ # Copyright 2018 Daniel Herzog
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Exceptions
8
+ class RequestError < Error
9
+ attr_reader :request, :response
10
+
11
+ def initialize(response)
12
+ super()
13
+ @response = response
14
+ end
15
+
16
+ def to_s
17
+ 'Unknown error.'
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,18 @@
1
+ # Copyright 2024 DeepL SE (https://www.deepl.com)
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Exceptions
8
+ class ServerError < RequestError
9
+ def to_s
10
+ 'An internal server error occured. Try again after waiting a short period.'
11
+ end
12
+
13
+ def should_retry?
14
+ true
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,38 @@
1
+ # Copyright 2022 Daniel Herzog
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ class GlossaryApi
8
+ def initialize(api, options = {})
9
+ @api = api
10
+ @options = options
11
+ end
12
+
13
+ def create(name, source_lang, target_lang, entries, options = {})
14
+ DeepL::Requests::Glossary::Create.new(@api, name, source_lang, target_lang, entries, options)
15
+ .request
16
+ end
17
+
18
+ def destroy(glossary_id, options = {})
19
+ DeepL::Requests::Glossary::Destroy.new(@api, glossary_id, options).request
20
+ end
21
+
22
+ def entries(glossary_id, options = {})
23
+ DeepL::Requests::Glossary::Entries.new(@api, glossary_id, options).request
24
+ end
25
+
26
+ def find(glossary_id, options = {})
27
+ DeepL::Requests::Glossary::Find.new(@api, glossary_id, options).request
28
+ end
29
+
30
+ def language_pairs(options = {})
31
+ DeepL::Requests::Glossary::LanguagePairs.new(@api, options).request
32
+ end
33
+
34
+ def list(options = {})
35
+ DeepL::Requests::Glossary::List.new(@api, options).request
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,212 @@
1
+ # Copyright 2018 Daniel Herzog
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Requests
8
+ class Base # rubocop:disable Metrics/ClassLength
9
+ attr_reader :api, :response, :options
10
+
11
+ def initialize(api, options = {}, additional_headers = {})
12
+ @api = api
13
+ @options = options
14
+ @additional_headers = additional_headers
15
+ @num_retries = 0
16
+ @backoff_timer = Utils::BackoffTimer.new
17
+ end
18
+
19
+ def request
20
+ raise NotImplementedError
21
+ end
22
+
23
+ def details
24
+ "HTTP Headers #{headers}"
25
+ end
26
+
27
+ private
28
+
29
+ def option?(name)
30
+ options.key?(name.to_s) || options.key?(name.to_sym)
31
+ end
32
+
33
+ def option(name)
34
+ options[name.to_s] || options[name.to_sym]
35
+ end
36
+
37
+ def delete_option(name)
38
+ options.delete(name.to_s) || options.delete(name.to_sym)
39
+ end
40
+
41
+ def set_option(name, value)
42
+ if options.key?(name.to_sym)
43
+ options[name.to_sym] = value
44
+ else
45
+ options[name.to_s] = value
46
+ end
47
+ end
48
+
49
+ # Returns options excluding extra_body_parameters
50
+ # extra_body_parameters are applied separately via apply_extra_body_parameters_* methods
51
+ def options_without_extra_params
52
+ options.reject do |k, _|
53
+ k.to_s == 'extra_body_parameters' || k.to_sym == :extra_body_parameters
54
+ end
55
+ end
56
+
57
+ # Apply extra body parameters to a hash payload (for JSON/form-encoded requests)
58
+ # Extra parameters will override existing keys
59
+ def apply_extra_body_parameters_to_json(payload)
60
+ return unless option?(:extra_body_parameters)
61
+
62
+ extra_params = option(:extra_body_parameters)
63
+ extra_params.each do |key, value|
64
+ payload[key] = value
65
+ end
66
+ end
67
+
68
+ # Apply extra body parameters to multipart form data array
69
+ # Extra parameters will override existing keys
70
+ def apply_extra_body_parameters_to_form(form_data)
71
+ return unless option?(:extra_body_parameters)
72
+
73
+ extra_params = option(:extra_body_parameters)
74
+ extra_params.each do |key, value|
75
+ key_str = key.to_s
76
+ # Remove existing key if present to allow override.
77
+ # Required for form data as it would be duplicated otherwise
78
+ form_data.reject! { |field| field[0].to_s == key_str }
79
+ form_data.push([key_str, value.to_s])
80
+ end
81
+ end
82
+
83
+ # Files to reset: list of file objects to rewind when retrying the request
84
+ def execute_request_with_retries(req, files_to_reset = []) # rubocop:disable all
85
+ api.configuration.logger&.info("Request to the DeepL API: #{self}")
86
+ api.configuration.logger&.debug("Request details: #{details}")
87
+ loop do
88
+ resp = api.http_client.request(req)
89
+ validate_response!(resp)
90
+ return [req, resp]
91
+ rescue DeepL::Exceptions::Error => e
92
+ raise e unless should_retry?(resp, e, @backoff_timer.num_retries)
93
+
94
+ unless e.nil?
95
+ api.configuration.logger&.info("Encountered a retryable exception: #{e.message}")
96
+ end
97
+ api.configuration.logger&.info("Starting retry #{@backoff_timer.num_retries + 1} for " \
98
+ "request #{request} after sleeping for " \
99
+ "#{format('%.2f', @backoff_timer.time_until_deadline)}")
100
+ files_to_reset.each(&:rewind)
101
+ @backoff_timer.sleep_until_deadline
102
+ next
103
+ rescue Net::HTTPBadResponse, Net::HTTPServerError, Net::HTTPFatalError, Timeout::Error,
104
+ SocketError => e
105
+ unless e.nil?
106
+ api.configuration.logger&.info("Encountered a retryable exception: #{e.message}")
107
+ end
108
+ api.configuration.logger&.info("Starting retry #{@backoff_timer.num_retries + 1} for " \
109
+ "request #{request} after sleeping for " \
110
+ "#{format('%.2f', @backoff_timer.time_until_deadline)}")
111
+ files_to_reset.each(&:rewind)
112
+ @backoff_timer.sleep_until_deadline
113
+ next
114
+ end
115
+ end
116
+
117
+ def should_retry?(response, exception, num_retries)
118
+ return false if num_retries >= api.configuration.max_network_retries
119
+ return exception.should_retry? if response.nil?
120
+
121
+ response.is_a?(Net::HTTPTooManyRequests) || response.is_a?(Net::HTTPInternalServerError)
122
+ end
123
+
124
+ def post_request(payload)
125
+ apply_extra_body_parameters_to_json(payload)
126
+ http_headers = add_json_content_type(headers)
127
+ post_req = Net::HTTP::Post.new(uri.path, http_headers)
128
+ post_req.body = payload.merge(options_without_extra_params).to_json
129
+ post_req
130
+ end
131
+
132
+ def post_request_with_file(form_data)
133
+ http_headers = add_multipart_form_content_type(headers)
134
+ post_req = Net::HTTP::Post.new(uri.request_uri, http_headers)
135
+ post_req.set_form(form_data, 'multipart/form-data')
136
+ post_req
137
+ end
138
+
139
+ def get_request # rubocop:disable Naming/AccessorMethodName
140
+ http_headers = add_json_content_type(headers)
141
+ get_req = Net::HTTP::Get.new(uri.path, http_headers)
142
+ get_req.body = options_without_extra_params.to_json
143
+ get_req
144
+ end
145
+
146
+ def patch_request(payload)
147
+ apply_extra_body_parameters_to_json(payload)
148
+ http_headers = add_json_content_type(headers)
149
+ req = Net::HTTP::Patch.new(uri.path, http_headers)
150
+ req.body = payload.merge(options_without_extra_params).to_json
151
+ req
152
+ end
153
+
154
+ def put_request(payload)
155
+ apply_extra_body_parameters_to_json(payload)
156
+ http_headers = add_json_content_type(headers)
157
+ req = Net::HTTP::Put.new(uri.path, http_headers)
158
+ req.body = payload.merge(options_without_extra_params).to_json
159
+ req
160
+ end
161
+
162
+ def delete_request
163
+ http_headers = add_json_content_type(headers)
164
+ del_req = Net::HTTP::Delete.new(uri.path, http_headers)
165
+ del_req.body = options_without_extra_params.to_json
166
+ del_req
167
+ end
168
+
169
+ def validate_response!(response)
170
+ return if response.is_a?(Net::HTTPSuccess)
171
+
172
+ raise Utils::ExceptionBuilder.new(response).build
173
+ end
174
+
175
+ def path
176
+ raise NotImplementedError
177
+ end
178
+
179
+ def url
180
+ "#{host}/#{api.configuration.version}/#{path}"
181
+ end
182
+
183
+ def uri
184
+ @uri ||= URI(url)
185
+ @uri
186
+ end
187
+
188
+ def host
189
+ api.configuration.host
190
+ end
191
+
192
+ def query_params
193
+ options
194
+ end
195
+
196
+ def headers
197
+ { 'Authorization' => "DeepL-Auth-Key #{api.configuration.auth_key}",
198
+ 'User-Agent' => api.configuration.user_agent }.merge(@additional_headers)
199
+ end
200
+
201
+ def add_json_content_type(headers_to_add_to)
202
+ headers_to_add_to['Content-Type'] = 'application/json'
203
+ headers_to_add_to
204
+ end
205
+
206
+ def add_multipart_form_content_type(headers_to_add_to)
207
+ headers_to_add_to['Content-Type'] = 'multipart/form-data'
208
+ headers_to_add_to
209
+ end
210
+ end
211
+ end
212
+ end
@@ -0,0 +1,44 @@
1
+ # Copyright 2024 DeepL SE (https://www.deepl.com)
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Requests
8
+ module Document
9
+ class Download < Base
10
+ attr_reader :document_id, :document_key
11
+
12
+ def initialize(api, document_id, document_key, output_file)
13
+ super(api, {})
14
+ @document_id = document_id
15
+ @document_key = document_key
16
+ @output_file = output_file
17
+ end
18
+
19
+ def request
20
+ payload = { document_key: document_key }
21
+ extract_file(*execute_request_with_retries(post_request(payload)))
22
+ end
23
+
24
+ def details
25
+ "HTTP Headers: #{headers}\nPayload #{{ document_key: document_key }}"
26
+ end
27
+
28
+ def to_s
29
+ "POST #{uri.request_uri}"
30
+ end
31
+
32
+ private
33
+
34
+ def extract_file(_request, response)
35
+ File.write(@output_file, response.body)
36
+ end
37
+
38
+ def path
39
+ "document/#{document_id}/result"
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end