adobe_pdfservices_ruby 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 897432d0fa7438d335b7ad8d890a55be8acde8246438b8f19d6cb777e99165e2
4
+ data.tar.gz: 3243b85b5629490c72938ce5f9f16681a6ad337a1114498a1f3bac327a5ec422
5
+ SHA512:
6
+ metadata.gz: d180ada893c3c9204f098446594b2e4a48933941c2e1c0118ec3503d4968f2c712d4c3936c80c7ff79e22695292723640f39a19f723453f201f8182c411a62cb
7
+ data.tar.gz: ed6ff19b9ccf5e44aefa4936e0d6ddae8107fd7901e9e62d4d7fd0b55c24ad06707143e054f269ff50fe7c82501a413dc5f0668d690d3464cd393ef3725a1abe
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ # The behavior of RuboCop can be controlled via the .rubocop.yml
2
+ # configuration file. It makes it possible to enable/disable
3
+ # certain cops (checks) and to alter their behavior if they accept
4
+ # any parameters. The file can be placed either in your home
5
+ # directory or in some project directory.
6
+ #
7
+ # RuboCop will start looking for the configuration file in the directory
8
+ # where the inspected file is and continue its way up to the root directory.
9
+ #
10
+ # See https://docs.rubocop.org/rubocop/configuration
11
+
12
+ Metrics/MethodLength:
13
+ Max: 25
@@ -0,0 +1,7 @@
1
+ {
2
+ "recommendations": [
3
+ "rebornix.ruby",
4
+ "oderwat.indent-rainbow",
5
+ "ms-vsliveshare.vsliveshare"
6
+ ]
7
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "editor.rulers": [
3
+ 100,
4
+ 120
5
+ ],
6
+ "files.exclude": {
7
+ "**/.git": true,
8
+ "**/.svn": true,
9
+ "**/.hg": true,
10
+ "**/.DS_Store": true,
11
+ "**/tmp": true
12
+ }
13
+ }
data/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-08-25
4
+
5
+ - Initial release
6
+
7
+ ## [0.1.1] - 2024-01-18
8
+
9
+ - Refactor for DRYness and use modern Ruby syntax
10
+ - Add support for PDF extraction
11
+ - Change usage to use a single client object
12
+ - EXPERIMENTAL: Add support for internal and external operations (OCR, htmltopdf, documentgeneration)
13
+ - Update tests
14
+ - Update README
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at jimmy@funkyboss.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in pdfservices-ruby-sdk.gemspec
6
+ gemspec
7
+
8
+ gem 'minitest', '~> 5.0'
9
+ gem 'rake', '~> 13.0'
10
+
11
+ group :test do
12
+ gem 'webmock', '~> 3.18'
13
+ end
14
+
15
+ gem 'dotenv', '~> 2.8', group: :development
16
+
17
+ gem 'rubocop', '~> 1.60'
data/Gemfile.lock ADDED
@@ -0,0 +1,79 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ adobe_pdfservices_ruby (0.1.1)
5
+ faraday (~> 2.9)
6
+ json (~> 2.6)
7
+ mimemagic (~> 0.4.3)
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ addressable (2.8.6)
13
+ public_suffix (>= 2.0.2, < 6.0)
14
+ ast (2.4.2)
15
+ crack (0.4.5)
16
+ rexml
17
+ dotenv (2.8.1)
18
+ faraday (2.9.0)
19
+ faraday-net_http (>= 2.0, < 3.2)
20
+ faraday-net_http (3.1.0)
21
+ net-http
22
+ hashdiff (1.1.0)
23
+ json (2.7.1)
24
+ language_server-protocol (3.17.0.3)
25
+ mimemagic (0.4.3)
26
+ nokogiri (~> 1)
27
+ rake
28
+ minitest (5.21.2)
29
+ net-http (0.4.1)
30
+ uri
31
+ nokogiri (1.16.0-arm64-darwin)
32
+ racc (~> 1.4)
33
+ nokogiri (1.16.0-x86_64-linux)
34
+ racc (~> 1.4)
35
+ parallel (1.24.0)
36
+ parser (3.3.0.4)
37
+ ast (~> 2.4.1)
38
+ racc
39
+ public_suffix (5.0.4)
40
+ racc (1.7.3)
41
+ rainbow (3.1.1)
42
+ rake (13.1.0)
43
+ regexp_parser (2.9.0)
44
+ rexml (3.2.6)
45
+ rubocop (1.60.1)
46
+ json (~> 2.3)
47
+ language_server-protocol (>= 3.17.0)
48
+ parallel (~> 1.10)
49
+ parser (>= 3.3.0.2)
50
+ rainbow (>= 2.2.2, < 4.0)
51
+ regexp_parser (>= 1.8, < 3.0)
52
+ rexml (>= 3.2.5, < 4.0)
53
+ rubocop-ast (>= 1.30.0, < 2.0)
54
+ ruby-progressbar (~> 1.7)
55
+ unicode-display_width (>= 2.4.0, < 3.0)
56
+ rubocop-ast (1.30.0)
57
+ parser (>= 3.2.1.0)
58
+ ruby-progressbar (1.13.0)
59
+ unicode-display_width (2.5.0)
60
+ uri (0.13.0)
61
+ webmock (3.19.1)
62
+ addressable (>= 2.8.0)
63
+ crack (>= 0.3.2)
64
+ hashdiff (>= 0.4.0, < 2.0.0)
65
+
66
+ PLATFORMS
67
+ arm64-darwin-21
68
+ x86_64-linux
69
+
70
+ DEPENDENCIES
71
+ adobe_pdfservices_ruby!
72
+ dotenv (~> 2.8)
73
+ minitest (~> 5.0)
74
+ rake (~> 13.0)
75
+ rubocop (~> 1.60)
76
+ webmock (~> 3.18)
77
+
78
+ BUNDLED WITH
79
+ 2.4.10
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Jimmy Bosse
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # PDF Services for Ruby
2
+
3
+ ### Originally forked from [Adobe Document Services PDF Tools SDK for Ruby](https://github.com/arpc/adobe_pdfservices_ruby)
4
+
5
+ This gem provides a Ruby wrapper for the [Adobe PDF Services API](https://developer.adobe.com/document-services/docs/overview/). It allows you to perform various PDF operations, such as extracting content from PDFs, OCR, HTML to PDF, and document generation.
6
+
7
+ ## Installation
8
+
9
+ 1. Add the gem to your gemfile:
10
+
11
+ ```ruby
12
+ gem "adobe_pdfservices_ruby"
13
+ ```
14
+
15
+ 2. Run `bundle install`
16
+
17
+ ## Usage Example
18
+
19
+ The `PdfServices::Client` class allows you to perform various PDF operations, such as extracting content from PDFs. The client supports real-time updates on the operation status and retrieves the resulting file upon completion. Below is an example of how to use the client to extract content from a PDF file:
20
+
21
+ ```ruby
22
+ require 'adobe_pdfservices_ruby'
23
+
24
+ # Initialize the client with your credentials
25
+ client = PdfServices::Client.new('your_client_id', 'your_client_secret')
26
+
27
+ # Path to the PDF file you want to extract content from
28
+ source_pdf = 'path/to/your/pdf/file.pdf'
29
+
30
+ # Set the options for your operation
31
+ options = { extract_elements: ['text', 'tables'] }
32
+
33
+ # Perform the operation with real-time status updates
34
+ client.extract_pdf(source_pdf, options) do |status, file|
35
+ if status == 'in progress'
36
+ puts "Current status: #{status}"
37
+ elsif status == 'done'
38
+ puts "Extraction complete! The resulting file is ready for download."
39
+ # Process or save the resulting file
40
+ File.open('extracted_result.pdf', 'w') { |f| f.write(file) }
41
+ else
42
+ puts "Current status: #{status}"
43
+ end
44
+ end
45
+
46
+ # Perform the operation and only retrieve the resulting file
47
+ file = client.extract_pdf(source_pdf, options)
48
+ ```
49
+
50
+ ## Development
51
+
52
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
53
+
54
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
55
+
56
+ ### Currently Supported
57
+
58
+ Work is in progress on getting the gem to support all of the operations available in the [Adobe PDF Services API](https://developer.adobe.com/document-services/docs/overview/). Below is a list of the operations and their current support status:
59
+
60
+ - ✅ Extract PDF
61
+ - ❗ OCR
62
+ - ❗ EXPERIMENTAL: Internal
63
+ - ❗ EXPERIMENTAL: External
64
+ - ❗ HTML to PDF
65
+ - ❗ EXPERIMENTAL: Internal
66
+ - ❗ EXPERIMENTAL: External
67
+ - ❗ Document Generation:
68
+ - ✅ Internal
69
+ - ❗ EXPERIMENTAL: External
70
+
71
+ ### Operation parameters
72
+
73
+ The parameters for each method are listed in the [Adobe PDF Services API documentation](https://developer.adobe.com/document-services/docs/overview/). The parameters are passed to the methods
74
+ as a hash.
75
+
76
+ For most operations that rely on a file as the first parameter, this can either be the path to the file or a File object.
77
+
78
+ ## Contributing
79
+
80
+ Bug reports and pull requests are welcome on GitHub at https://github.com/benterova/adobe_pdfservices_ruby. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/benterova/adobe_pdfservices_ruby/blob/main/CODE_OF_CONDUCT.md).
81
+
82
+ ## License
83
+
84
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
85
+
86
+ ## Code of Conduct
87
+
88
+ Be good. [code of conduct](https://github.com/benterova/adobe_pdfservices_ruby/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rake/testtask'
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << 'test'
8
+ t.libs << 'lib'
9
+ test_file = ARGV[1]
10
+ files = FileList['test/**/*_test.rb']
11
+ t.test_files = test_file ? files.grep(/#{test_file}/) : files
12
+ end
13
+
14
+ require 'standard/rake'
15
+
16
+ task default: %i[test standard]
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/pdfservices/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'adobe_pdfservices_ruby'
7
+ spec.version = PdfServices::VERSION
8
+ spec.authors = ['Jimmy Bosse', 'Ben Terova']
9
+ spec.email = ['jimmy.bosse@ankura.com', 'ben@benterova.com']
10
+
11
+ spec.summary = 'Adobe PDF Services Ruby'
12
+ spec.description = 'An Adobe PDF Services Ruby SDK provides APIs for creating, combining, exporting and manipulating PDFs.'
13
+ spec.homepage = 'https://github.com/benterova/adobe_pdfservices_ruby/blob/main/README.md'
14
+ spec.license = 'MIT'
15
+ spec.required_ruby_version = '>= 3.0.0'
16
+
17
+ spec.metadata['homepage_uri'] = spec.homepage
18
+ spec.metadata['source_code_uri'] = 'https://github.com/benterova/adobe_pdfservices_ruby'
19
+ spec.metadata['changelog_uri'] = 'https://github.com/benterova/adobe_pdfservices_ruby/blob/main/CHANGELOG.md'
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(__dir__) do
24
+ `git ls-files -z`.split("\x0").reject do |f|
25
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
26
+ end
27
+ end
28
+ spec.require_paths = ['lib']
29
+
30
+ # Uncomment to register a new dependency of your gem
31
+ # spec.add_dependency "example-gem", "~> 1.0"
32
+ spec.add_dependency 'faraday', '~> 2.9'
33
+ spec.add_dependency 'json', '~> 2.6'
34
+ spec.add_dependency 'mimemagic', '~> 0.4.3'
35
+
36
+ # For more information and examples about making a new gem, check out our
37
+ # guide at: https://bundler.io/guides/creating_gem.html
38
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'multipart_parser/reader'
5
+ require 'yaml'
6
+ require 'faraday'
7
+ require 'mimemagic'
8
+
9
+ # Errors
10
+ require_relative 'pdfservices/errors'
11
+
12
+ # Asset
13
+ require_relative 'pdfservices/asset'
14
+
15
+ # Base
16
+ require_relative 'pdfservices/operations/base'
17
+
18
+ # Internal/External Operations
19
+ require_relative 'pdfservices/operations/internal_external_operation'
20
+
21
+ # Document Generation
22
+ require_relative 'pdfservices/operations/document_generation'
23
+ require_relative 'pdfservices/operations/document_generation/internal'
24
+ require_relative 'pdfservices/operations/document_generation/external'
25
+
26
+ # OCR
27
+ require_relative 'pdfservices/operations/ocr'
28
+
29
+ # HTML to PDF
30
+ require_relative 'pdfservices/operations/html_to_pdf'
31
+
32
+ # Extract PDF
33
+ require_relative 'pdfservices/operations/extract_pdf'
34
+
35
+ # Client and API
36
+ require_relative 'pdfservices/client'
37
+ require_relative 'pdfservices/api'
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PdfServices
4
+ class Api
5
+ attr_accessor :access_token
6
+
7
+ def initialize(access_token = nil, client_id = nil)
8
+ @access_token = access_token
9
+ @client_id = client_id
10
+
11
+ @connection = Faraday.new do |conn|
12
+ conn.request :url_encoded
13
+ conn.adapter Faraday.default_adapter
14
+ end
15
+ end
16
+
17
+ def post(url, body:, headers: {})
18
+ response = @connection.post(url) do |req|
19
+ build_request(req, headers, body)
20
+ end
21
+ handle_response(response)
22
+ end
23
+
24
+ def get(url, headers: {})
25
+ response = @connection.get(url) do |req|
26
+ build_request(req, headers, nil)
27
+ end
28
+ handle_response(response)
29
+ end
30
+
31
+ def put(url, body:, headers: {})
32
+ response = @connection.put(url) do |req|
33
+ build_request(req, headers, body)
34
+ end
35
+ handle_response(response)
36
+ end
37
+
38
+ def delete(url, headers: {})
39
+ response = @connection.delete(url) do |req|
40
+ build_headers(req, headers)
41
+ end
42
+ handle_response(response)
43
+ end
44
+
45
+ private
46
+
47
+ def build_request(request, headers, body = nil)
48
+ request.body = transform_body(body) if body
49
+ request.headers = build_headers(request, headers)
50
+ end
51
+
52
+ def build_headers(request, headers = {})
53
+ default_headers = { 'X-Api-Key' => @client_id }
54
+
55
+ # Adobe only allows one authorization type, and presigned URLs already have the token in the URL
56
+ # so we only add the Authorization header if it's not a presigned URL
57
+ default_headers['Authorization'] = "Bearer #{@access_token}" if request.params['X-Amz-Credential'].nil?
58
+
59
+ default_headers = default_headers.merge(headers) unless headers.empty?
60
+ default_headers
61
+ end
62
+
63
+ def transform_body(body)
64
+ body.is_a?(Hash) ? body.to_json : body
65
+ end
66
+
67
+ def handle_response(response)
68
+ # Implement response handling logic here, like error checking
69
+ response
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,74 @@
1
+ module PdfServices
2
+ class Asset
3
+ ASSETS_ENDPOINT = 'https://pdf-services-ue1.adobe.io/assets'.freeze
4
+
5
+ attr_reader :id
6
+
7
+ def initialize(api, id = nil)
8
+ raise ArgumentError, 'Api is nil' unless api
9
+
10
+ @api = api
11
+ @id = id
12
+ end
13
+
14
+ def upload(file, media_type: 'application/pdf')
15
+ url = presigned_url(media_type:)
16
+ upload_uri = url['uploadUri']
17
+ asset_id = url['assetID']
18
+
19
+ response = @api.put(upload_uri, body: File.new(file), headers: upload_headers(File.new(file)))
20
+
21
+ unless response.status == 200
22
+ raise AssetError,
23
+ "Something went wrong when trying to upload the file: #{response.body.inspect}"
24
+ end
25
+
26
+ @id = asset_id
27
+
28
+ self
29
+ end
30
+
31
+ def download(asset_id = nil)
32
+ raise AssetError, 'Asset ID is nil' unless @id || asset_id
33
+ raise AssetError, "Asset ID is not a string, is a #{@id.class}" unless (@id || asset_id).respond_to?(:to_s)
34
+
35
+ @id = asset_id if asset_id
36
+
37
+ url = presigned_url(:download)
38
+ download_uri = url['downloadUri']
39
+ @api.get(download_uri)
40
+ end
41
+
42
+ def delete
43
+ raise AssetError, 'Asset ID is nil' unless @id
44
+
45
+ @api.delete("#{ASSETS_ENDPOINT}/#{@id}")
46
+ end
47
+
48
+ private
49
+
50
+ def upload_headers(file)
51
+ {
52
+ 'Content-Type' => MimeMagic.by_magic(file).type,
53
+ 'Content-Length' => file.size.to_s
54
+ }
55
+ end
56
+
57
+ def presigned_url(operation = :upload, media_type: 'application/pdf')
58
+ case operation
59
+ when :upload
60
+ response = @api.post(ASSETS_ENDPOINT, body: { mediaType: media_type },
61
+ headers: { 'Content-Type' => 'application/json' })
62
+ when :download
63
+ response = @api.get("#{ASSETS_ENDPOINT}/#{@id}")
64
+ end
65
+
66
+ unless response.status == 200
67
+ raise AssetError,
68
+ "Something went wrong when trying to get the presigned URL: #{JSON.parse(response.body)}"
69
+ end
70
+
71
+ JSON.parse response.body.to_s
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PdfServices
4
+ class Client
5
+ TOKEN_ENDPOINT = 'https://pdf-services-ue1.adobe.io/token'
6
+ DEFAULT_TOKEN_DURATION = 86_399
7
+ attr_reader :expires_at
8
+
9
+ def initialize(client_id = nil, client_secret = nil, access_token = nil)
10
+ @client_id = client_id
11
+ @client_secret = client_secret
12
+ @access_token = access_token
13
+ @expires_at = Time.now + DEFAULT_TOKEN_DURATION
14
+ valid_access_token? ? access_token : refresh_token
15
+ validate_client
16
+ @api = Api.new(@access_token, @client_id)
17
+ end
18
+
19
+ def method_missing(method_name, *args, &block)
20
+ operation_class_name = "PdfServices::#{camelize(method_name.to_s)}::Operation"
21
+ if Object.const_defined? operation_class_name
22
+ operation_class = Object.const_get operation_class_name
23
+ operation = operation_class.new @api
24
+ operation.execute(*args, &block)
25
+ else
26
+ super
27
+ end
28
+ end
29
+
30
+ def respond_to_missing?(method_name, include_private = false)
31
+ operation_class_name = "PdfServices::#{camelize(method_name.to_s)}::Operation"
32
+ Object.const_defined?(operation_class_name) || super
33
+ end
34
+
35
+ private
36
+
37
+ def camelize(str)
38
+ str.split('_').map(&:capitalize).join
39
+ end
40
+
41
+ def validate_client
42
+ raise 'Client ID and Client Secret are required' if (@client_id.nil? || @client_secret.nil?) && @access_token.nil?
43
+ end
44
+
45
+ def valid_access_token?
46
+ !@access_token.nil? && Time.now <= @expires_at
47
+ end
48
+
49
+ def refresh_token
50
+ response = Faraday.post(TOKEN_ENDPOINT) do |req|
51
+ req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
52
+ req.body = {
53
+ client_id: @client_id,
54
+ client_secret: @client_secret
55
+ }
56
+ unless response.status == 200
57
+ raise ClientError,
58
+ "Something went wrong when trying to refresh the token: #{response.body}"
59
+ end
60
+ end
61
+
62
+ raise "Token refresh error: #{response.status} - #{response.body}" unless response.status == 200
63
+
64
+ response_json = JSON.parse(response.body)
65
+ @access_token = response_json['access_token']
66
+ @expires_at = Time.now + response_json['expires_in'].to_i
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,16 @@
1
+ module PdfServices
2
+ class Error < StandardError
3
+ end
4
+
5
+ class AssetError < Error
6
+ end
7
+
8
+ class PollingError < Error
9
+ end
10
+
11
+ class OperationError < Error
12
+ end
13
+
14
+ class ClientError < Error
15
+ end
16
+ end