switchfile-sdk 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: da22008a6b321b1dc7b74e57e94d41f49661daff6b6ead51721d2ef63bbb7807
4
+ data.tar.gz: f4ef68cd85cc8112800458786cfaee55334b7be30b3d97218760129db0a6327c
5
+ SHA512:
6
+ metadata.gz: b6e8354361e4ac979326600b424dd7f2d2d3da4c4b47bb7b17cd23c62def4f336d047c9bd77cadbd64b8f6bd831b8b0ac08b53eedc364aa9ff0da367e6d68616
7
+ data.tar.gz: 0d6950733e21ce431234edb966272c5e5e4197bcb79666395e87cf93813f306edfa86ee4a7eccf3e75da957f43cb70bee6183bad6f16f93e565f327fe8110f12
data/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First release.
6
+
7
+ - `jobs` (`create`, `find`, `all`, `wait`, `delete`), `tasks` (`find`, `all`, `wait`, `cancel`, `retry`, `upload`),
8
+ `users.me` and `download` with the same names as the CloudConvert gem.
9
+ - `convert` for one-call conversions, with `conversions.find`, `wait` and `delete`.
10
+ - `Switchfile::Webhook` to verify signatures, plus `Webhook::Processor` for Rails controllers.
11
+ - Retries after network errors, `429` and server errors; `sandbox: true` refuses live keys.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aura UG (haftungsbeschränkt)
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,192 @@
1
+ # switchfile for Ruby
2
+
3
+ The official Ruby SDK for the [switchfile](https://switchfile.io) file conversion API.
4
+
5
+ - The same classes and methods as the CloudConvert gem (`jobs.create`, `jobs.wait`, `tasks.upload`, `download`,
6
+ `Webhook.verify` and more), so existing code keeps working after you change the module name and the key.
7
+ - `convert` for the simple API: one call with a file and a target format, and you get the finished conversion back.
8
+ - No dependencies, only the Ruby standard library. Ruby 3.1 or newer.
9
+
10
+ ```bash
11
+ gem install switchfile-sdk
12
+ ```
13
+
14
+ In a Gemfile: `gem "switchfile-sdk"`. The code stays `require "switchfile"`.
15
+
16
+ ## Quick start
17
+
18
+ ```ruby
19
+ require "switchfile"
20
+
21
+ switchfile = Switchfile::Client.new(api_key: ENV["SWITCHFILE_API_KEY"])
22
+
23
+ conversion = switchfile.convert("talk.mkv", "mp4")
24
+ switchfile.download(conversion, destination: "talk.mp4")
25
+ ```
26
+
27
+ Create an API key in the [dashboard](https://switchfile.io/dashboard/keys). Keys starting with `sf_test_` are
28
+ sandbox keys: they never use credits.
29
+
30
+ ## Coming from CloudConvert
31
+
32
+ Change the module name and the key. Everything else stays the same.
33
+
34
+ ```diff
35
+ - require "cloudconvert"
36
+ - cloudconvert = CloudConvert::Client.new(api_key: ENV["CLOUDCONVERT_API_KEY"], sandbox: false)
37
+ + require "switchfile"
38
+ + cloudconvert = Switchfile::Client.new(api_key: ENV["SWITCHFILE_API_KEY"], sandbox: false)
39
+ ```
40
+
41
+ Errors move from `CloudConvert::Error` to `Switchfile::Error` with the same subclasses (`Error::ClientError`,
42
+ `Error::NotFound`, `Error::UnprocessableEntity`, `Error::ServerError`, ...). `CloudConvert::Webhook` becomes
43
+ `Switchfile::Webhook`, `CloudConvert::File` becomes `Switchfile::File`.
44
+
45
+ What is different:
46
+
47
+ | CloudConvert | switchfile |
48
+ |---|---|
49
+ | `sandbox: true` uses a separate sandbox server | The key decides: `sf_test_` keys are sandbox keys. `sandbox: true` refuses live keys, so tests cannot use credits by mistake |
50
+ | `CLOUDCONVERT_API_KEY`, `CLOUDCONVERT_SANDBOX` | `SWITCHFILE_API_KEY`, `SWITCHFILE_SANDBOX` |
51
+ | Depends on faraday, down, activesupport and others | No dependencies |
52
+ | `download` returns a `Tempfile` from the down gem | Returns a `Tempfile`, or a `File` with `destination:` |
53
+ | Operations such as `optimize`, `merge`, `capture-website`, `import/s3` | Tasks: `import/url`, `import/upload`, `import/base64`, `convert`, `export/url` |
54
+ | `tasks.create`, `tasks.delete` | Not available; create tasks inside a job with `jobs.create` |
55
+ | `CloudConvert::SignedUrl` | Not available |
56
+
57
+ ## Convert a file in one call
58
+
59
+ ```ruby
60
+ conversion = switchfile.convert(
61
+ File.open("photo.heic"),
62
+ "jpg",
63
+ { quality: 80 }, # settings for the conversion
64
+ webhook_url: "https://example.com/hooks/switchfile",
65
+ wait: true, # false: return right away with status "queued"
66
+ timeout: 600 # stop waiting after 10 minutes
67
+ )
68
+
69
+ conversion.result.files.each do |file| # e.g. one image per page
70
+ switchfile.download(file.url, destination: file.filename).close
71
+ end
72
+ ```
73
+
74
+ `convert(file, to, options, ...)` takes a path, an open `IO`, `Switchfile::File`, a public URL as a string
75
+ (`"https://..."`) or `{ url: }`, `{ upload_id: }`, `{ from: conversion_id }` to convert an earlier input again, or
76
+ `{ content: bytes, filename: "a.png" }`.
77
+
78
+ Files up to 50 MB are sent with the request; larger files go through an upload URL and are read from disk while they
79
+ upload. The call waits until the conversion is done and raises `Switchfile::ConversionFailed` if it fails. Further
80
+ keyword arguments: `filename:`, `input_format:`, `preset:` (ID or name of a preset from the dashboard; `to` may then
81
+ be `nil`), `idempotency_key:`.
82
+
83
+ ```ruby
84
+ switchfile.conversions.find(conversion.id)
85
+ switchfile.conversions.wait(conversion.id, timeout: 600)
86
+ switchfile.conversions.delete(conversion.id) # delete input and result right away
87
+ ```
88
+
89
+ ## Jobs and tasks
90
+
91
+ ```ruby
92
+ job = switchfile.jobs.create({
93
+ tasks: [
94
+ { name: "import-my-file", operation: "import/url", url: "https://example.com/report.docx" },
95
+ { name: "convert-my-file", operation: "convert", input: "import-my-file", output_format: "pdf" },
96
+ { name: "export-my-file", operation: "export/url", input: "convert-my-file" }
97
+ ],
98
+ tag: "order-42"
99
+ })
100
+
101
+ job = switchfile.jobs.wait(job.id)
102
+ job.export_urls.each do |file|
103
+ switchfile.download(file.url, destination: file.filename).close
104
+ end
105
+ ```
106
+
107
+ `tasks` is an array of tasks with a `name`, as in the CloudConvert gem, or a hash of name to task.
108
+
109
+ ### Uploading files
110
+
111
+ ```ruby
112
+ job = switchfile.jobs.create({ tasks: [{ name: "upload-my-file", operation: "import/upload" }, ...] })
113
+ upload_task = job.tasks.where(operation: "import/upload").first
114
+
115
+ switchfile.tasks.upload("/path/to/sample.pdf", upload_task)
116
+ switchfile.tasks.upload(File.open("/path/to/sample.pdf"), upload_task)
117
+ switchfile.tasks.upload(Switchfile::File.new(io, "application/pdf", "sample.pdf"), upload_task)
118
+ ```
119
+
120
+ ### All methods
121
+
122
+ | Method | API |
123
+ |---|---|
124
+ | `jobs.create(params)`, `jobs.find(id)`, `jobs.all(params)`, `jobs.wait(id, timeout:)`, `jobs.delete(id)` | `/v2/jobs` |
125
+ | `tasks.find(id)`, `tasks.all(params)`, `tasks.wait(id, timeout:)`, `tasks.cancel(id)`, `tasks.retry(id)`, `tasks.upload(file, task)` | `/v2/tasks` |
126
+ | `users.me` | `/v2/users/me` |
127
+ | `convert(...)`, `conversions.find/wait/delete` | `/v1/convert`, `/v1/conversions` |
128
+ | `download(url_or_conversion, destination:)` | result files |
129
+
130
+ Jobs, tasks and conversions are read-only objects: `job.tasks`, `task.result.files.first.url` or `task["result"]`.
131
+ `job.status` and `task.status` are symbols (`:finished`), with `task.finished?` and so on.
132
+
133
+ ## Webhooks
134
+
135
+ ```ruby
136
+ payload = request.body.read
137
+ signature = request.headers["CloudConvert-Signature"] || request.headers["Switchfile-Signature"]
138
+
139
+ if Switchfile::Webhook.verify(payload, signature, ENV["SWITCHFILE_WEBHOOK_SIGNING_SECRET"])
140
+ event = Switchfile::Webhook.event(payload)
141
+ event.name # "job.finished", "job.failed", "conversion.finished", "conversion.failed"
142
+ event.job # for job events
143
+ event.conversion # for conversion events
144
+ end
145
+ ```
146
+
147
+ `verify_request(request, secret)` takes a Rack request, `verify!` and `verify_request!` raise
148
+ `Switchfile::Webhook::InvalidSignature` instead of returning `false`. In Rails, include
149
+ `Switchfile::Webhook::Processor` in a controller and define `job_finished(event)`, `conversion_finished(event)` and
150
+ `webhook_secret(event)`, as with `CloudConvert::Webhook::Processor`.
151
+
152
+ Jobs sign with the header `CloudConvert-Signature`, conversions from `convert` with `Switchfile-Signature`; both use
153
+ HMAC-SHA256 of the raw body. The signing secret is in the dashboard.
154
+
155
+ ## Settings
156
+
157
+ ```ruby
158
+ switchfile = Switchfile::Client.new(
159
+ api_key: "...", # default: SWITCHFILE_API_KEY
160
+ sandbox: true, # only accept sandbox keys (sf_test_); default: SWITCHFILE_SANDBOX
161
+ base_url: "https://api.switchfile.io", # default: SWITCHFILE_API_URL or https://api.switchfile.io
162
+ timeout: 60, # per request, in seconds
163
+ max_retries: 3, # network errors, 429 and 5xx
164
+ user_agent: "my-app/1.0" # added to the User-Agent header
165
+ )
166
+ ```
167
+
168
+ Requests are repeated after network errors, `429 RATE_LIMIT_EXCEEDED` (after `Retry-After`) and server errors.
169
+ `convert` sends an `Idempotency-Key`, so a repeated request never creates a second conversion.
170
+
171
+ ## Errors
172
+
173
+ Every error is a `Switchfile::Error` with a stable `code` (for example `UNAUTHENTICATED`, `INVALID_DATA`,
174
+ `UNSUPPORTED_PAIR`, `CREDITS_EXCEEDED`, `RATE_LIMIT_EXCEEDED`), the HTTP `status` and, for `INVALID_DATA`, `errors` per
175
+ field.
176
+
177
+ ```ruby
178
+ begin
179
+ switchfile.convert("notes.txt", "mp4")
180
+ rescue Switchfile::ConversionFailed => e
181
+ puts "failed: #{e.code} #{e.conversion.id}"
182
+ rescue Switchfile::Error => e
183
+ puts "#{e.status} #{e.code} #{e.message}"
184
+ end
185
+ ```
186
+
187
+ ## Links
188
+
189
+ - [API documentation](https://switchfile.io/developers)
190
+ - [Supported formats](https://switchfile.io/convert)
191
+
192
+ License: MIT, Aura UG (haftungsbeschränkt).
@@ -0,0 +1,159 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "securerandom"
5
+
6
+ module Switchfile
7
+ # Entry point, as CloudConvert::Client.new(api_key: ..., sandbox: ...).
8
+ class Client
9
+ DEFAULT_BASE_URL = "https://api.switchfile.io"
10
+ # Files up to this size go with the request (multipart), larger ones through POST /v1/uploads.
11
+ MULTIPART_LIMIT = 50 * 1024 * 1024
12
+ # Request time limit without storage (seconds): upload 120 s, conversion 90 s, sending the answer 180 s.
13
+ NO_STORE_TIMEOUT = 390
14
+
15
+ attr_reader :api_key, :sandbox
16
+
17
+ # Options: api_key (default SWITCHFILE_API_KEY), sandbox (default SWITCHFILE_SANDBOX), base_url (default
18
+ # SWITCHFILE_API_URL or https://api.switchfile.io), timeout (seconds per request, 60), max_retries (3),
19
+ # poll_interval (seconds, 1.0), user_agent (added to the header), region (accepted and ignored).
20
+ def initialize(options = {})
21
+ o = options.transform_keys(&:to_sym)
22
+ @api_key = (o.key?(:api_key) ? o[:api_key] : ENV.fetch("SWITCHFILE_API_KEY", "")).to_s.strip
23
+ @sandbox = o.key?(:sandbox) ? o[:sandbox] == true : ENV["SWITCHFILE_SANDBOX"].to_s.downcase == "true"
24
+ base = (o[:base_url] || ENV.fetch("SWITCHFILE_API_URL", nil) || DEFAULT_BASE_URL).to_s
25
+ raise Error.new("Invalid base URL: #{base}", "INVALID_BASE_URL") unless base.match?(%r{\Ahttps?://[^/\s]+}i)
26
+
27
+ if @sandbox && @api_key.match?(/\A(sf_live_|ac_live_)/)
28
+ raise Error.new("Sandbox mode needs a sandbox key (sf_test_...). Create one in the dashboard under API keys.",
29
+ "SANDBOX_KEY_REQUIRED")
30
+ end
31
+
32
+ ua = "switchfile-ruby/#{VERSION}#{o[:user_agent] ? " #{o[:user_agent]}" : ''}"
33
+ @http = HTTP.new(api_key: @api_key, base_url: base.sub(%r{/+\z}, ""), timeout: (o[:timeout] || 60).to_f,
34
+ max_retries: (o[:max_retries] || 3).to_i, user_agent: ua)
35
+ @poll = (o[:poll_interval] || 1.0).to_f
36
+ end
37
+
38
+ def jobs
39
+ @jobs ||= Resources::Jobs.new(@http, @poll)
40
+ end
41
+
42
+ def tasks
43
+ @tasks ||= Resources::Tasks.new(@http, @poll)
44
+ end
45
+
46
+ def users
47
+ @users ||= Resources::Users.new(@http)
48
+ end
49
+
50
+ # /v1/conversions: find, wait, delete.
51
+ def conversions
52
+ @conversions ||= Resources::Conversions.new(@http, @poll)
53
+ end
54
+
55
+ # Convert a file (/v1) and, by default, wait for the result. Raises ConversionFailed if the conversion fails.
56
+ #
57
+ # file: a path, an open IO, Switchfile::File, a public URL ("https://..."), { url: }, { upload_id: },
58
+ # { from: conversion_id } or { content: bytes, filename: }.
59
+ # options: settings of the conversion, e.g. { quality: 80 }.
60
+ def convert(file, to = nil, options = {}, filename: nil, input_format: nil, webhook_url: nil, preset: nil,
61
+ wait: true, timeout: 1800, idempotency_key: nil, multipart_limit: MULTIPART_LIMIT)
62
+ to = to.to_s
63
+ if to.empty? && preset.to_s.empty?
64
+ raise Error.new("The target format (to) is missing. Pass a format or a preset.", "INVALID_DATA")
65
+ end
66
+
67
+ key = idempotency_key || SecureRandom.uuid
68
+ query = { wait: wait ? Resources::Conversions::WAIT_SECONDS : nil }
69
+ req_timeout = @http.timeout + (wait ? Resources::Conversions::WAIT_SECONDS : 0)
70
+ fields = {}
71
+ fields["to"] = to unless to.empty?
72
+ fields["options"] = options unless options.nil? || options.empty?
73
+ { "input_format" => input_format, "webhook_url" => webhook_url, "preset" => preset }.each do |k, v|
74
+ fields[k] = v.to_s unless v.nil?
75
+ end
76
+
77
+ json = json_source(file)
78
+ conv =
79
+ if json
80
+ body = json.merge(fields)
81
+ body["filename"] = filename if filename
82
+ @http.request("POST", "/v1/convert", query: query, json: body, idempotency_key: key, timeout: req_timeout)
83
+ else
84
+ source = file.is_a?(Hash) ? Source.bytes(file[:content] || file["content"], filename || file[:filename] || file["filename"]) : Source.from(file, filename)
85
+ begin
86
+ send_file(source, fields, query, key, req_timeout, multipart_limit)
87
+ ensure
88
+ source.close
89
+ end
90
+ end
91
+ conv = Record.new(conv)
92
+ return conv unless wait
93
+ return Resources::Conversions.assert_finished(conv) if %w[finished failed].include?(conv.status)
94
+
95
+ conversions.wait(conv.id, timeout: timeout)
96
+ end
97
+
98
+ # Download a result: a URL, a file from result.files, or a finished conversion (its first file). Returns a
99
+ # Tempfile, or with `destination:` a File at that path. Both are open for reading at position 0.
100
+ def download(url, destination: nil)
101
+ if url.is_a?(Record) || url.is_a?(Hash)
102
+ rec = Record.wrap(url)
103
+ url = rec.download_url || rec.url
104
+ end
105
+ raise Error.new("Nothing to download: the conversion has no result file yet.", "NO_FILE") if url.to_s.empty?
106
+
107
+ @http.download(url, destination)
108
+ end
109
+
110
+ def self.put_headers(headers)
111
+ out = {}
112
+ headers.each do |k, v|
113
+ next if v.nil? || v.is_a?(Hash) || v.is_a?(Array)
114
+
115
+ value = v.to_s
116
+ # Values with CR, LF or NUL are dropped, not repaired.
117
+ next if value.match?(/[\r\n\0]/)
118
+ next unless k.to_s.match?(/\A[A-Za-z0-9-]{1,64}\z/)
119
+ next if k.to_s.match?(/\A(authorization|host|content-length|transfer-encoding|connection|cookie)\z/i)
120
+
121
+ out[k.to_s] = value
122
+ end
123
+ out["Content-Type"] = "application/octet-stream" unless out.keys.any? { |k| k.casecmp?("content-type") }
124
+ out
125
+ end
126
+
127
+ private
128
+
129
+ def send_file(source, fields, query, key, req_timeout, multipart_limit)
130
+ if source.size <= multipart_limit
131
+ form = lambda do
132
+ parts = fields.map { |k, v| [k, k == "options" ? JSON.generate(v) : v] }
133
+ parts << ["filename", source.filename] if source.filename
134
+ parts << source.part
135
+ end
136
+ return @http.request("POST", "/v1/convert", query: query, form: form, idempotency_key: key,
137
+ timeout: [req_timeout, 1800].max)
138
+ end
139
+ up_body = { size: source.size }
140
+ up_body[:filename] = source.filename if source.filename
141
+ up = @http.request("POST", "/v1/uploads", json: up_body, idempotency_key: "#{key}:upload")
142
+ @http.put_signed(up["url"], source.io, source.size, Client.put_headers(up["headers"] || {}))
143
+ body = { "upload_id" => up["upload_id"] }.merge(fields)
144
+ body["filename"] = source.filename if source.filename
145
+ @http.request("POST", "/v1/convert", query: query, json: body, idempotency_key: key, timeout: req_timeout)
146
+ end
147
+
148
+ def json_source(file)
149
+ return { "url" => file } if file.is_a?(String) && file.match?(%r{\Ahttps?://}i)
150
+ return nil unless file.is_a?(Hash)
151
+
152
+ h = file.transform_keys(&:to_s)
153
+ return nil if h.key?("content")
154
+
155
+ %w[url upload_id from].each { |k| return { k => h[k].to_s } if h[k] }
156
+ raise Error.new("Pass { url: }, { upload_id: }, { from: } or { content:, filename: }.", "INVALID_SOURCE")
157
+ end
158
+ end
159
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Switchfile
4
+ # Base class of all errors. `code` is the stable code of the API (INVALID_DATA, UNAUTHENTICATED, NOT_FOUND, ...)
5
+ # or of the client (NETWORK_ERROR, TIMEOUT, ...). The subclasses carry the same names as in the CloudConvert gem.
6
+ class Error < StandardError
7
+ attr_reader :code, :errors, :status, :retry_after, :body
8
+
9
+ ClientError = Class.new(self)
10
+ BadRequest = Class.new(ClientError)
11
+ Unauthorized = Class.new(ClientError)
12
+ PaymentRequired = Class.new(ClientError)
13
+ Forbidden = Class.new(ClientError)
14
+ NotFound = Class.new(ClientError)
15
+ NotAcceptable = Class.new(ClientError)
16
+ Conflict = Class.new(ClientError)
17
+ RequestEntityTooLarge = Class.new(ClientError)
18
+ UnprocessableEntity = Class.new(ClientError)
19
+ TooManyRequests = Class.new(ClientError)
20
+ NetworkError = Class.new(ClientError)
21
+
22
+ ServerError = Class.new(self)
23
+ InternalServerError = Class.new(ServerError)
24
+ BadGateway = Class.new(ServerError)
25
+ ServiceUnavailable = Class.new(ServerError)
26
+ GatewayTimeout = Class.new(ServerError)
27
+
28
+ TimeoutError = Class.new(self)
29
+
30
+ ERRORS = {
31
+ 400 => BadRequest, 401 => Unauthorized, 402 => PaymentRequired, 403 => Forbidden, 404 => NotFound,
32
+ 406 => NotAcceptable, 409 => Conflict, 413 => RequestEntityTooLarge, 422 => UnprocessableEntity,
33
+ 429 => TooManyRequests, 500 => InternalServerError, 502 => BadGateway, 503 => ServiceUnavailable,
34
+ 504 => GatewayTimeout
35
+ }.freeze
36
+
37
+ FALLBACK_CODES = {
38
+ 401 => "UNAUTHENTICATED", 403 => "FORBIDDEN", 404 => "NOT_FOUND", 413 => "FILE_TOO_LARGE",
39
+ 422 => "INVALID_DATA", 429 => "RATE_LIMIT_EXCEEDED"
40
+ }.freeze
41
+
42
+ def self.from_response(status, data, retry_after = nil)
43
+ body = data.is_a?(Hash) ? data : {}
44
+ code = body["code"].is_a?(String) && !body["code"].empty? ? body["code"] : nil
45
+ code ||= status >= 500 ? "INTERNAL_ERROR" : FALLBACK_CODES.fetch(status, "HTTP_ERROR")
46
+ message = %w[detail message title].map { |k| body[k] }.find { |v| v.is_a?(String) && !v.empty? }
47
+ message ||= "The switchfile API answered with HTTP #{status}."
48
+ klass = ERRORS[status] || (status >= 500 ? ServerError : ClientError)
49
+ ra = retry_after.to_s.match?(/\A\d+(\.\d+)?\z/) ? retry_after.to_f : nil
50
+ errors = body["errors"].is_a?(Hash) ? body["errors"] : nil
51
+ klass.new(message, code, errors, status: status, retry_after: ra, body: data)
52
+ end
53
+
54
+ def initialize(message = "", code = nil, errors = nil, status: nil, retry_after: nil, body: nil)
55
+ super(message)
56
+ @code = code || "ERROR"
57
+ @errors = errors
58
+ @status = status
59
+ @retry_after = retry_after
60
+ @body = body
61
+ end
62
+ end
63
+
64
+ # A conversion from `convert` failed. `conversion` is the whole conversion.
65
+ class ConversionFailed < Error
66
+ attr_reader :conversion
67
+
68
+ def initialize(message, code, conversion)
69
+ super(message, code, nil, body: conversion)
70
+ @conversion = conversion
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "stringio"
4
+
5
+ module Switchfile
6
+ # A file with its own name and content type, as CloudConvert::File: `Switchfile::File.new(io_or_path, "image/png",
7
+ # "photo.png")`.
8
+ class File
9
+ attr_reader :file, :content_type, :filename
10
+
11
+ def initialize(file, content_type = nil, filename = nil)
12
+ @file = file
13
+ @content_type = content_type
14
+ @filename = filename
15
+ end
16
+ end
17
+
18
+ # Upload source for paths, IO objects, Switchfile::File and raw bytes. Files are read while they are sent.
19
+ class Source
20
+ attr_reader :filename, :content_type, :size
21
+
22
+ def self.from(file, filename = nil)
23
+ return new(file.file, filename || file.filename, file.content_type) if file.is_a?(Switchfile::File)
24
+
25
+ new(file, filename)
26
+ end
27
+
28
+ def self.bytes(data, filename)
29
+ new(StringIO.new(data.to_s.b), filename)
30
+ end
31
+
32
+ def initialize(file, filename = nil, content_type = nil)
33
+ @content_type = content_type || "application/octet-stream"
34
+ if file.is_a?(String) || file.is_a?(Pathname)
35
+ path = file.to_s
36
+ raise Error.new("File not found: #{path}", "FILE_NOT_FOUND") unless ::File.file?(path)
37
+
38
+ @io = ::File.open(path, "rb")
39
+ @owned = true
40
+ @filename = filename || ::File.basename(path)
41
+ elsif file.respond_to?(:read)
42
+ @io = file
43
+ @owned = false
44
+ @filename = filename || (file.respond_to?(:path) && file.path ? ::File.basename(file.path.to_s) : nil)
45
+ else
46
+ raise Error.new("Pass a path, an IO object or Switchfile::File.", "INVALID_SOURCE")
47
+ end
48
+ @io.binmode if @io.respond_to?(:binmode)
49
+ @start = @io.respond_to?(:pos) ? @io.pos : 0
50
+ @size = measure
51
+ end
52
+
53
+ # The IO at the start position, for each attempt.
54
+ def io
55
+ @io.seek(@start) if @io.respond_to?(:seek)
56
+ @io
57
+ end
58
+
59
+ def part(name = "file")
60
+ [name, io, { filename: @filename || "file", content_type: @content_type }]
61
+ end
62
+
63
+ def close
64
+ @io.close if @owned && !@io.closed?
65
+ end
66
+
67
+ private
68
+
69
+ def measure
70
+ return @io.size - @start if @io.respond_to?(:size)
71
+ return @io.stat.size - @start if @io.respond_to?(:stat)
72
+
73
+ raise Error.new("The size of the file is unknown. Pass a path or a File.", "INVALID_SOURCE")
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,237 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "openssl"
6
+ require "tempfile"
7
+ require "uri"
8
+
9
+ module Switchfile
10
+ # HTTP over Net::HTTP without other dependencies. The API key only goes to the API base URL, never to signed
11
+ # upload and download URLs. Redirects of the API are errors, not followed.
12
+ class HTTP
13
+ attr_reader :base_url, :timeout
14
+
15
+ def initialize(api_key:, base_url:, timeout:, max_retries:, user_agent:)
16
+ @api_key = api_key
17
+ @base_url = base_url
18
+ @timeout = timeout
19
+ @max_retries = max_retries
20
+ @user_agent = user_agent
21
+ end
22
+
23
+ # Nested hashes become bracket keys as with the CloudConvert gem (Faraday): { filter: { tag: "a" } } ->
24
+ # filter[tag]=a. Arrays are joined with commas, the API reads include=retries,payload, not include[].
25
+ def self.flatten_query(value, prefix = nil)
26
+ case value
27
+ when Hash
28
+ value.flat_map { |k, v| flatten_query(v, prefix ? "#{prefix}[#{k}]" : k.to_s) }
29
+ when Array
30
+ value.empty? ? [] : [[prefix, value.join(",")]]
31
+ when nil
32
+ []
33
+ else
34
+ [[prefix, value.to_s]]
35
+ end
36
+ end
37
+
38
+ # JSON request to the API. `form` is a lambda that returns the multipart parts for each attempt, so streams can be
39
+ # rewound for a retry. Returns the decoded body (nil for 204); with `binary: true` [body, headers].
40
+ def request(method, path, query: nil, json: nil, form: nil, auth: true, idempotency_key: nil, retry_server: nil,
41
+ timeout: nil, headers: {})
42
+ uri = URI.parse(@base_url + path)
43
+ q = HTTP.flatten_query(query || {})
44
+ uri.query = URI.encode_www_form(q) unless q.empty?
45
+ if auth && @api_key.empty?
46
+ raise Error.new("No API key. Pass api_key or set SWITCHFILE_API_KEY.", "MISSING_API_KEY")
47
+ end
48
+
49
+ retry_server = %w[GET DELETE].include?(method) || !idempotency_key.nil? if retry_server.nil?
50
+ attempt = 0
51
+ loop do
52
+ req = new_request(method, uri, { "Accept" => "application/json" }.merge(headers))
53
+ req["Authorization"] = "Bearer #{@api_key}" if auth
54
+ req["Idempotency-Key"] = idempotency_key if idempotency_key
55
+ if json
56
+ req["Content-Type"] = "application/json"
57
+ req.body = JSON.generate(json)
58
+ elsif form
59
+ req.set_form(form.call, "multipart/form-data")
60
+ end
61
+ begin
62
+ res = perform(uri, req, timeout || @timeout)
63
+ rescue Error::NetworkError, Error::TimeoutError
64
+ raise unless retry_server && attempt < @max_retries
65
+
66
+ sleep(backoff(attempt))
67
+ attempt += 1
68
+ next
69
+ end
70
+ status = res.code.to_i
71
+ raise redirect_error(status, res["location"], uri) if status >= 300 && status < 400
72
+
73
+ data = decode(res.body)
74
+ return status == 204 ? nil : data if status >= 200 && status < 300
75
+
76
+ err = Error.from_response(status, data, res["retry-after"])
77
+ again = (status == 429 && err.code == "RATE_LIMIT_EXCEEDED") ||
78
+ (status == 409 && err.code == "IDEMPOTENCY_KEY_IN_USE") ||
79
+ (retry_server && [500, 502, 503, 504].include?(status))
80
+ if again && attempt < @max_retries
81
+ wait = err.retry_after || backoff(attempt)
82
+ if wait <= 60
83
+ sleep(wait)
84
+ attempt += 1
85
+ next
86
+ end
87
+ end
88
+ raise err
89
+ end
90
+ end
91
+
92
+ # PUT a file to a signed URL (no key). `io` is read while it is sent.
93
+ def put_signed(url, io, size, headers)
94
+ uri = resolve_signed(url)
95
+ req = new_request("PUT", uri, headers)
96
+ req.body_stream = io
97
+ req["Content-Length"] = size.to_s
98
+ res = perform(uri, req, [@timeout, 3600].max)
99
+ status = res.code.to_i
100
+ raise Error.from_response(status, decode(res.body), res["retry-after"]) unless status >= 200 && status < 300
101
+
102
+ nil
103
+ end
104
+
105
+ # POST a multipart form to a signed URL (no key), as for the form of an import/upload task.
106
+ def post_form_signed(url, parts)
107
+ uri = resolve_signed(url)
108
+ req = new_request("POST", uri, { "Accept" => "application/json" })
109
+ req.set_form(parts, "multipart/form-data")
110
+ res = perform(uri, req, [@timeout, 3600].max)
111
+ status = res.code.to_i
112
+ data = decode(res.body)
113
+ raise Error.from_response(status, data, res["retry-after"]) unless status >= 200 && status < 300
114
+
115
+ data
116
+ end
117
+
118
+ # Download a signed URL (no key) into `destination` or a Tempfile. Returns the open file at position 0.
119
+ def download(url, destination = nil)
120
+ uri = resolve_signed(url)
121
+ attempt = 0
122
+ loop do
123
+ tmp = Tempfile.new("switchfile", destination ? ::File.dirname(destination) : Dir.tmpdir, binmode: true)
124
+ begin
125
+ status, raw, headers = fetch_to(uri, tmp)
126
+ rescue Error::NetworkError, Error::TimeoutError
127
+ tmp.close!
128
+ raise unless attempt < @max_retries
129
+
130
+ sleep(backoff(attempt))
131
+ attempt += 1
132
+ next
133
+ end
134
+ if status >= 200 && status < 300
135
+ tmp.flush
136
+ return rewound(tmp) unless destination
137
+
138
+ tmp.close
139
+ ::File.rename(tmp.path, destination)
140
+ return ::File.open(destination, "rb")
141
+ end
142
+ tmp.close!
143
+ if status >= 500 && attempt < @max_retries
144
+ sleep(backoff(attempt))
145
+ attempt += 1
146
+ next
147
+ end
148
+ raise Error.from_response(status, decode(raw), headers["retry-after"])
149
+ end
150
+ end
151
+
152
+ def resolve_signed(url)
153
+ url = url.to_s
154
+ url = "#{@base_url}/#{url.sub(%r{\A/+}, '')}" unless url.match?(%r{\A[a-z][a-z0-9+.-]*:}i)
155
+ uri = URI.parse(url)
156
+ unless %w[http https].include?(uri.scheme&.downcase) && uri.userinfo.nil? && uri.host
157
+ raise Error.new("The switchfile API returned a file URL that is not allowed.", "BAD_RESPONSE")
158
+ end
159
+
160
+ uri
161
+ rescue URI::InvalidURIError
162
+ raise Error.new("The switchfile API returned a file URL that is not allowed.", "BAD_RESPONSE")
163
+ end
164
+
165
+ private
166
+
167
+ def rewound(file)
168
+ file.rewind
169
+ file
170
+ end
171
+
172
+ def new_request(method, uri, headers)
173
+ klass = { "GET" => Net::HTTP::Get, "POST" => Net::HTTP::Post, "PUT" => Net::HTTP::Put,
174
+ "PATCH" => Net::HTTP::Patch, "DELETE" => Net::HTTP::Delete }.fetch(method)
175
+ req = klass.new(uri)
176
+ req["User-Agent"] = @user_agent
177
+ headers.each { |k, v| req[k] = v }
178
+ req
179
+ end
180
+
181
+ def connection(uri, timeout)
182
+ http = Net::HTTP.new(uri.host, uri.port)
183
+ http.use_ssl = uri.scheme == "https"
184
+ http.open_timeout = 30
185
+ http.read_timeout = timeout
186
+ http.write_timeout = timeout
187
+ http
188
+ end
189
+
190
+ def perform(uri, req, timeout)
191
+ guard(uri) { connection(uri, timeout).start { |h| h.request(req) } }
192
+ end
193
+
194
+ def fetch_to(uri, file)
195
+ req = new_request("GET", uri, {})
196
+ guard(uri) do
197
+ connection(uri, [@timeout, 3600].max).start do |h|
198
+ h.request(req) do |res|
199
+ status = res.code.to_i
200
+ if status >= 200 && status < 300
201
+ res.read_body { |chunk| file.write(chunk) }
202
+ return [status, nil, res.to_hash.transform_values(&:first)]
203
+ end
204
+ return [status, res.read_body, res.to_hash.transform_values(&:first)]
205
+ end
206
+ end
207
+ end
208
+ end
209
+
210
+ def guard(uri)
211
+ yield
212
+ rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout
213
+ raise Error::TimeoutError.new("The request to #{uri.host} did not finish in time.", "TIMEOUT")
214
+ rescue SocketError, SystemCallError, IOError, EOFError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse
215
+ raise Error::NetworkError.new("Could not reach #{uri.host}.", "NETWORK_ERROR")
216
+ end
217
+
218
+ def redirect_error(status, location, uri)
219
+ host = uri.port == uri.default_port ? uri.host : "#{uri.host}:#{uri.port}"
220
+ target = location.to_s.empty? ? "" : " to #{location}"
221
+ Error.new("The switchfile API at #{host} answered with a redirect (HTTP #{status}#{target}). Check the base " \
222
+ "URL; it should be https://api.switchfile.io.", "UNEXPECTED_REDIRECT", status: status)
223
+ end
224
+
225
+ def decode(raw)
226
+ return nil if raw.nil? || raw.empty?
227
+
228
+ JSON.parse(raw)
229
+ rescue JSON::ParserError
230
+ nil
231
+ end
232
+
233
+ def backoff(attempt)
234
+ [8.0, 0.5 * (2**attempt)].min + rand * 0.25
235
+ end
236
+ end
237
+ end
@@ -0,0 +1,155 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module Switchfile
6
+ # Read-only view of an API object: `record.result.files.first.url` and `record["result"]`. Unknown keys are nil,
7
+ # as with the OpenStruct objects of the CloudConvert gem.
8
+ class Record
9
+ def self.wrap(value)
10
+ case value
11
+ when Record then value
12
+ when Hash then Record.new(value)
13
+ when Array then value.map { |v| wrap(v) }
14
+ else value
15
+ end
16
+ end
17
+
18
+ attr_reader :attrs
19
+
20
+ def initialize(attrs = {})
21
+ @attrs = (attrs || {}).transform_keys(&:to_s)
22
+ end
23
+
24
+ def [](key)
25
+ Record.wrap(@attrs[key.to_s])
26
+ end
27
+
28
+ def key?(key)
29
+ @attrs.key?(key.to_s)
30
+ end
31
+
32
+ def to_h
33
+ @attrs
34
+ end
35
+ alias to_hash to_h
36
+
37
+ def ==(other)
38
+ other.is_a?(Record) && other.to_h == to_h
39
+ end
40
+
41
+ def inspect
42
+ "#<#{self.class.name} #{@attrs.inspect}>"
43
+ end
44
+
45
+ def method_missing(name, *args)
46
+ key = name.to_s
47
+ return super unless args.empty? && key.match?(/\A[a-z_][a-z0-9_]*\z/)
48
+
49
+ Record.wrap(@attrs[key])
50
+ end
51
+
52
+ def respond_to_missing?(name, include_private = false)
53
+ @attrs.key?(name.to_s) || super
54
+ end
55
+
56
+ private
57
+
58
+ def time(key)
59
+ v = @attrs[key]
60
+ v.nil? ? nil : Time.parse(v).utc
61
+ end
62
+ end
63
+
64
+ # Array of models with `links`, `meta` and `where(operation: "import/upload")` as in the CloudConvert gem.
65
+ class Collection < Array
66
+ attr_reader :links, :meta
67
+
68
+ def self.from(response, klass)
69
+ new(Array(response && response["data"]).map { |item| klass.new(item) }, Record.wrap(response && response["links"]),
70
+ Record.wrap(response && response["meta"]))
71
+ end
72
+
73
+ def initialize(items = [], links = nil, meta = nil)
74
+ super(items)
75
+ @links = links
76
+ @meta = meta
77
+ end
78
+
79
+ def where(attrs)
80
+ self.class.new(select { |item| attrs.all? { |k, v| item.public_send(k) == v } }, links, meta)
81
+ end
82
+ end
83
+
84
+ class Task < Record
85
+ def status
86
+ @attrs["status"]&.to_sym
87
+ end
88
+
89
+ # With include: "retries" (tasks.find, tasks.all): the retries of this task.
90
+ def retries
91
+ Collection.new(Array(@attrs["retries"]).map { |t| Task.new(t) })
92
+ end
93
+
94
+ %i[waiting processing finished error].each do |s|
95
+ define_method(:"#{s}?") { status == s }
96
+ end
97
+
98
+ def created_at
99
+ time("created_at")
100
+ end
101
+
102
+ def started_at
103
+ time("started_at")
104
+ end
105
+
106
+ def ended_at
107
+ time("ended_at")
108
+ end
109
+ end
110
+
111
+ class Job < Record
112
+ def status
113
+ @attrs["status"]&.to_sym
114
+ end
115
+
116
+ def tasks
117
+ Collection.new(Array(@attrs["tasks"]).map { |t| Task.new(t) })
118
+ end
119
+
120
+ # Files of all finished export/url tasks (filename, size, url).
121
+ def export_urls
122
+ tasks.where(operation: "export/url", status: :finished).flat_map { |t| Array(t.result&.files) }
123
+ end
124
+
125
+ def created_at
126
+ time("created_at")
127
+ end
128
+
129
+ def started_at
130
+ time("started_at")
131
+ end
132
+
133
+ def ended_at
134
+ time("ended_at")
135
+ end
136
+ end
137
+
138
+ class User < Record; end
139
+
140
+ # Webhook payload: `event.name` ("job.finished", "conversion.finished", ...), `event.job` or `event.conversion`.
141
+ class Event < Record
142
+ def event
143
+ @attrs["event"]
144
+ end
145
+ alias name event
146
+
147
+ def job
148
+ @attrs["job"].is_a?(Hash) ? Job.new(@attrs["job"]) : nil
149
+ end
150
+
151
+ def conversion
152
+ @attrs["data"].is_a?(Hash) ? Record.new(@attrs["data"]) : nil
153
+ end
154
+ end
155
+ end
@@ -0,0 +1,193 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "erb"
4
+
5
+ module Switchfile
6
+ module Resources
7
+ # Repeated GET until a final status, with a growing pause up to 5 seconds.
8
+ module Poll
9
+ def self.until(timeout, interval)
10
+ deadline = timeout && (Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout)
11
+ loop do
12
+ item = yield
13
+ return item if item
14
+
15
+ pause = interval
16
+ if deadline
17
+ left = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
18
+ raise Error::TimeoutError.new("Still not finished after waiting #{timeout} seconds.", "TIMEOUT") if left <= 0
19
+
20
+ pause = [pause, left].min
21
+ end
22
+ sleep(pause)
23
+ interval = [5.0, interval * 1.5].min
24
+ end
25
+ end
26
+ end
27
+
28
+ def self.enc(id)
29
+ ERB::Util.url_encode(id.to_s)
30
+ end
31
+
32
+ # /v2/jobs with the methods of `cloudconvert.jobs`.
33
+ class Jobs
34
+ def initialize(http, poll_interval)
35
+ @http = http
36
+ @poll = poll_interval
37
+ end
38
+
39
+ def all(params = {})
40
+ Collection.from(@http.request("GET", "/v2/jobs", query: params), Job)
41
+ end
42
+
43
+ def find(id, params = {})
44
+ Job.new(@http.request("GET", "/v2/jobs/#{Resources.enc(id)}", query: params)["data"])
45
+ end
46
+
47
+ # `tasks` is an Array of tasks with a `name` (as in the CloudConvert gem) or a Hash of name => task.
48
+ # With `store: false` the job runs without storage and comes back finished, with the files in `content`.
49
+ def create(params)
50
+ payload = params.transform_keys(&:to_s)
51
+ tasks = payload["tasks"]
52
+ if tasks.is_a?(Array)
53
+ payload["tasks"] = tasks.to_h do |t|
54
+ t = t.transform_keys(&:to_s)
55
+ [t.fetch("name") { raise Error.new("Every task needs a name.", "INVALID_DATA") }, t.except("name")]
56
+ end
57
+ end
58
+ raise Error.new("A job needs at least one task.", "INVALID_DATA") if payload["tasks"].nil? || payload["tasks"].empty?
59
+
60
+ if payload["store"] == false
61
+ # The header raises the JSON body limit to the limit without storage (base64 of 50 MB).
62
+ res = @http.request("POST", "/sync/v2/jobs", json: payload, retry_server: false,
63
+ timeout: [@http.timeout, Client::NO_STORE_TIMEOUT].max,
64
+ headers: { "Switchfile-Store" => "false" })
65
+ return Job.new(res["data"])
66
+ end
67
+ # POST /v2/jobs has no idempotency key: only 429 is repeated (then the API created nothing).
68
+ Job.new(@http.request("POST", "/v2/jobs", json: payload, retry_server: false)["data"])
69
+ end
70
+
71
+ # Polls until the job is finished or error. Does not raise on error.
72
+ def wait(id, timeout: nil)
73
+ data = Poll.until(timeout, @poll) do
74
+ d = @http.request("GET", "/v2/jobs/#{Resources.enc(id)}")["data"]
75
+ d if %w[finished error].include?(d["status"])
76
+ end
77
+ Job.new(data)
78
+ end
79
+
80
+ def delete(id)
81
+ @http.request("DELETE", "/v2/jobs/#{Resources.enc(id)}")
82
+ nil
83
+ end
84
+ end
85
+
86
+ # /v2/tasks with the methods of `cloudconvert.tasks`.
87
+ class Tasks
88
+ def initialize(http, poll_interval)
89
+ @http = http
90
+ @poll = poll_interval
91
+ end
92
+
93
+ def all(params = {})
94
+ Collection.from(@http.request("GET", "/v2/tasks", query: params), Task)
95
+ end
96
+
97
+ def find(id, params = {})
98
+ Task.new(@http.request("GET", "/v2/tasks/#{Resources.enc(id)}", query: params)["data"])
99
+ end
100
+
101
+ def wait(id, timeout: nil)
102
+ data = Poll.until(timeout, @poll) do
103
+ d = @http.request("GET", "/v2/tasks/#{Resources.enc(id)}")["data"]
104
+ d if %w[finished error].include?(d["status"])
105
+ end
106
+ Task.new(data)
107
+ end
108
+
109
+ def cancel(id)
110
+ Task.new(@http.request("POST", "/v2/tasks/#{Resources.enc(id)}/cancel", retry_server: true)["data"])
111
+ end
112
+
113
+ # Returns the new task.
114
+ def retry(id)
115
+ Task.new(@http.request("POST", "/v2/tasks/#{Resources.enc(id)}/retry", retry_server: false)["data"])
116
+ end
117
+
118
+ # Upload a file for an import/upload task: a path, an open IO or Switchfile::File. Uses the direct upload
119
+ # (result.upload) if the API offers it, else the form (result.form). Returns the updated task.
120
+ def upload(file, task, filename = nil)
121
+ raise ArgumentError, "The task operation is not import/upload" unless task.operation == "import/upload"
122
+
123
+ source = Source.from(file, filename)
124
+ begin
125
+ if task.result&.upload&.url
126
+ headers = Client.put_headers(task.result.upload.headers&.to_h || {})
127
+ @http.put_signed(task.result.upload.url, source.io, source.size, headers)
128
+ body = source.filename ? { filename: source.filename } : {}
129
+ return Task.new(@http.request("POST", "/v2/tasks/#{Resources.enc(task.id)}/upload-complete", json: body,
130
+ retry_server: true)["data"])
131
+ end
132
+ raise ArgumentError, "The task is not ready for uploading" unless task.result&.form&.url
133
+
134
+ parts = (task.result.form.parameters&.to_h || {}).map { |k, v| [k.to_s, v.to_s] } + [source.part]
135
+ res = @http.post_form_signed(task.result.form.url, parts)
136
+ return Task.new(res["data"]) if res.is_a?(Hash) && res["data"].is_a?(Hash)
137
+
138
+ find(task.id)
139
+ ensure
140
+ source.close
141
+ end
142
+ end
143
+ end
144
+
145
+ class Users
146
+ def initialize(http)
147
+ @http = http
148
+ end
149
+
150
+ def me
151
+ User.new(@http.request("GET", "/v2/users/me")["data"])
152
+ end
153
+ end
154
+
155
+ # /v1/conversions: conversions from `convert`.
156
+ class Conversions
157
+ WAIT_SECONDS = 30
158
+
159
+ def initialize(http, poll_interval)
160
+ @http = http
161
+ @poll = poll_interval
162
+ end
163
+
164
+ # `wait`: wait up to this many seconds (at most 30) for the end.
165
+ def find(id, wait: nil)
166
+ w = wait&.positive? ? [WAIT_SECONDS, wait].min : nil
167
+ Record.new(@http.request("GET", "/v1/conversions/#{Resources.enc(id)}", query: { wait: w },
168
+ timeout: @http.timeout + (w || 0)))
169
+ end
170
+
171
+ # Waits until the conversion is finished. Raises ConversionFailed if it fails.
172
+ def wait(id, timeout: nil)
173
+ conv = Poll.until(timeout, @poll) do
174
+ c = find(id, wait: WAIT_SECONDS)
175
+ c if %w[finished failed].include?(c.status)
176
+ end
177
+ self.class.assert_finished(conv)
178
+ end
179
+
180
+ def delete(id)
181
+ @http.request("DELETE", "/v1/conversions/#{Resources.enc(id)}")
182
+ nil
183
+ end
184
+
185
+ def self.assert_finished(conv)
186
+ return conv unless conv.status == "failed"
187
+
188
+ err = conv.error
189
+ raise ConversionFailed.new(err&.message || "The conversion failed.", err&.code || "CONVERSION_FAILED", conv)
190
+ end
191
+ end
192
+ end
193
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Switchfile
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "openssl"
5
+
6
+ module Switchfile
7
+ # Webhook signatures as CloudConvert::Webhook: HMAC-SHA256 (hex) of the raw body with the signing secret, in the
8
+ # header CloudConvert-Signature (/v2 jobs) or Switchfile-Signature (/v1 conversions).
9
+ class Webhook
10
+ Error = Class.new(Switchfile::Error)
11
+ InvalidSignature = Class.new(Error)
12
+ MissingSignature = Class.new(Error)
13
+
14
+ class << self
15
+ def event(payload)
16
+ data = JSON.parse(payload.to_s)
17
+ raise Error.new("The webhook payload has no event name.", "INVALID_PAYLOAD") unless data.is_a?(Hash) && data["event"].is_a?(String)
18
+
19
+ Event.new(data)
20
+ rescue JSON::ParserError
21
+ raise Error.new("The webhook payload is not valid JSON.", "INVALID_PAYLOAD")
22
+ end
23
+
24
+ def verify(payload, signature, secret)
25
+ return false if signature.to_s.empty? || secret.to_s.empty?
26
+
27
+ expected = OpenSSL::HMAC.hexdigest("SHA256", secret.to_s, payload.to_s)
28
+ given = signature.to_s.strip.downcase
29
+ expected.bytesize == given.bytesize && OpenSSL.fixed_length_secure_compare(expected, given)
30
+ end
31
+
32
+ def verify!(payload, signature, secret)
33
+ raise MissingSignature.new("Missing webhook signature", "MISSING_SIGNATURE") if signature.to_s.empty?
34
+ raise InvalidSignature.new("Invalid webhook signature", "INVALID_SIGNATURE") unless verify(payload, signature, secret)
35
+
36
+ true
37
+ end
38
+
39
+ # Rack request (Rails, Sinatra): reads the body and the signature header.
40
+ def verify_request(request, secret)
41
+ verify(read_body(request), signature_of(request), secret)
42
+ end
43
+
44
+ def verify_request!(request, secret)
45
+ verify!(read_body(request), signature_of(request), secret)
46
+ end
47
+
48
+ def signature_of(request)
49
+ sig = request.get_header("HTTP_CLOUDCONVERT_SIGNATURE") if request.respond_to?(:get_header)
50
+ sig = request.get_header("HTTP_SWITCHFILE_SIGNATURE") if sig.to_s.empty? && request.respond_to?(:get_header)
51
+ sig
52
+ end
53
+
54
+ private
55
+
56
+ def read_body(request)
57
+ request.body.rewind
58
+ body = request.body.read
59
+ request.body.rewind
60
+ body
61
+ end
62
+ end
63
+
64
+ # Rails controller concern as CloudConvert::Webhook::Processor: checks the signature and calls `job_finished(event)`,
65
+ # `job_failed(event)`, `conversion_finished(event)` and so on. The controller defines `webhook_secret(event)`.
66
+ module Processor
67
+ UnspecifiedSecret = Class.new(Webhook::Error)
68
+
69
+ def self.included(base)
70
+ base.before_action :authenticate_switchfile_request!, only: :create if base.respond_to?(:before_action)
71
+ return unless base.respond_to?(:skip_before_action)
72
+
73
+ base.skip_before_action :verify_authenticity_token, only: :create, raise: false
74
+ end
75
+
76
+ def create
77
+ method = event.name.tr(".", "_")
78
+ raise NoMethodError, "#{self.class.name}##{method} not implemented" unless respond_to?(method, true)
79
+
80
+ send(method, event)
81
+ head(:ok)
82
+ end
83
+
84
+ private
85
+
86
+ def event
87
+ @event ||= Webhook.event(payload)
88
+ end
89
+
90
+ def payload
91
+ @payload ||= request.body.tap(&:rewind).read
92
+ end
93
+
94
+ def authenticate_switchfile_request!
95
+ secret = webhook_secret(event)
96
+ raise UnspecifiedSecret.new("webhook_secret is required", "MISSING_SECRET") if secret.to_s.empty?
97
+
98
+ Webhook.verify!(payload, Webhook.signature_of(request), secret)
99
+ rescue Webhook::Error
100
+ head(:bad_request)
101
+ end
102
+
103
+ def webhook_secret(_event)
104
+ raise NotImplementedError, "Implement webhook_secret(event) in #{self.class.name}"
105
+ end
106
+ end
107
+ end
108
+ end
data/lib/switchfile.rb ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+
5
+ require "switchfile/version"
6
+ require "switchfile/error"
7
+ require "switchfile/record"
8
+ require "switchfile/file"
9
+ require "switchfile/http"
10
+ require "switchfile/resources"
11
+ require "switchfile/webhook"
12
+ require "switchfile/client"
13
+
14
+ # Ruby SDK for the switchfile file conversion API, with the methods of the CloudConvert gem.
15
+ module Switchfile
16
+ end
metadata ADDED
@@ -0,0 +1,55 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: switchfile-sdk
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Aura UG (haftungsbeschränkt)
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Ruby SDK for the switchfile file conversion API. The same methods as
13
+ the CloudConvert gem (jobs, tasks, uploads, webhooks), plus convert() for one-call
14
+ conversions. No dependencies.
15
+ email: hello@switchfile.io
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - CHANGELOG.md
21
+ - LICENSE
22
+ - README.md
23
+ - lib/switchfile.rb
24
+ - lib/switchfile/client.rb
25
+ - lib/switchfile/error.rb
26
+ - lib/switchfile/file.rb
27
+ - lib/switchfile/http.rb
28
+ - lib/switchfile/record.rb
29
+ - lib/switchfile/resources.rb
30
+ - lib/switchfile/version.rb
31
+ - lib/switchfile/webhook.rb
32
+ homepage: https://switchfile.io/developers#sdks
33
+ licenses:
34
+ - MIT
35
+ metadata:
36
+ documentation_uri: https://switchfile.io/developers
37
+ changelog_uri: https://switchfile.io/developers#sdks
38
+ rdoc_options: []
39
+ require_paths:
40
+ - lib
41
+ required_ruby_version: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - ">="
44
+ - !ruby/object:Gem::Version
45
+ version: '3.1'
46
+ required_rubygems_version: !ruby/object:Gem::Requirement
47
+ requirements:
48
+ - - ">="
49
+ - !ruby/object:Gem::Version
50
+ version: '0'
51
+ requirements: []
52
+ rubygems_version: 4.0.20
53
+ specification_version: 4
54
+ summary: Ruby SDK for the switchfile file conversion API
55
+ test_files: []