Class: Rev::Api
- Inherits:
-
Object
- Object
- Rev::Api
- Defined in:
- lib/rev-api/api.rb
Overview
Main point of interaction with API. Wraps common REST operations, returning plain objects. Internally utilizes JSON resource representation.
Constant Summary collapse
- PRODUCTION_HOST =
Production host. Used by default for new Rev::Api client
'www.rev.com'- SANDBOX_HOST =
Sandbox domain - pass ‘Rev::Api::SANDBOX_HOST’ as third param into Rev::Api ctor
'api-sandbox.rev.com'
Class Method Summary collapse
-
.handle_error(response) ⇒ Object
Given a response, raises a corresponding Exception.
-
.parse(response) ⇒ Hash
Parse given response’s body JSON into Hash, so that it might be easily mapped onto business logic object.
-
.verify_get_response(response) ⇒ Boolean
Raises exception if response is not considered as success.
- .verify_post_response(response) ⇒ Object
Instance Method Summary collapse
-
#cancel_order(number) ⇒ Boolean
Cancel an order by number.
-
#create_input_from_link(url, filename = nil, content_type = nil) ⇒ String
Request creation of a source input based on an external URL which the server will attempt to download.
-
#get_all_orders ⇒ Array of Order
Loads all orders for current client.
-
#get_attachment_content(id, mime_type = nil) {|resp| ... } ⇒ Net::HTTP::Response
Get the raw data for the attachment with given id.
-
#get_attachment_content_as_string(id) ⇒ String
Get the content of the attachment with given id as a string.
-
#get_attachment_metadata(id) ⇒ Attachment
Get metadata about an order attachment.
-
#get_order(number) ⇒ Order
Returns Order given an order number.
-
#get_orders_page(page = 0) ⇒ OrdersListPage
Loads single page of existing orders for current client.
-
#initialize(client_api_key, user_api_key, host = PRODUCTION_HOST) ⇒ HttpClient
constructor
Client obj.
-
#save_attachment_content(id, path, mime_type = nil) ⇒ String
Get the raw data for the attachment with given id.
-
#submit_order(order_request) ⇒ String
Submit a new order using OrderRequest.
-
#upload_input(path, content_type) ⇒ String
Upload given local file directly as source input for order.
Constructor Details
#initialize(client_api_key, user_api_key, host = PRODUCTION_HOST) ⇒ HttpClient
Returns client obj.
30 31 32 |
# File 'lib/rev-api/api.rb', line 30 def initialize(client_api_key, user_api_key, host = PRODUCTION_HOST) @client = HttpClient.new(client_api_key, user_api_key, host) end |
Class Method Details
.handle_error(response) ⇒ Object
Given a response, raises a corresponding Exception. Full response is given for the sake of BadRequest reporting, which usually contains validation errors.
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 |
# File 'lib/rev-api/api.rb', line 287 def handle_error(response) case response.response when Net::HTTPBadRequest # Bad request - response contains error code and details. Usually means failed validation body = JSON.load response.body.to_s msg = "API responded with code #{body['code']}: #{body['message']}" msg += " Details: #{body['detail'].to_s}" if body['detail'] raise BadRequestError.new msg, body['code'] when Net:: raise NotAuthorizedError when Net::HTTPForbidden raise ForbiddenError when Net::HTTPNotFound raise NotFoundError when Net::HTTPNotAcceptable raise NotAcceptableError when Net::HTTPServerError raise ServerError, "Status code: #{response.code}" else raise UnknownError end end |
.parse(response) ⇒ Hash
Parse given response’s body JSON into Hash, so that it might be easily mapped onto business logic object.
254 255 256 |
# File 'lib/rev-api/api.rb', line 254 def parse(response) JSON.load response.body.to_s end |
.verify_get_response(response) ⇒ Boolean
Raises exception if response is not considered as success
262 263 264 265 266 267 268 269 270 |
# File 'lib/rev-api/api.rb', line 262 def verify_get_response(response) # HTTP response codes are handled here and propagated up to the caller, since caller should be able # to handle all types of errors the same - using exceptions unless response.response.instance_of? Net::HTTPOK Api.handle_error(response) end true end |
.verify_post_response(response) ⇒ Object
273 274 275 276 277 278 279 280 |
# File 'lib/rev-api/api.rb', line 273 def verify_post_response(response) # see http://www.rev.com/api/errorhandling unless response.response.instance_of?(Net::HTTPCreated) || response.response.instance_of?(Net::HTTPNoContent) Api.handle_error(response) end true end |
Instance Method Details
#cancel_order(number) ⇒ Boolean
Cancel an order by number. If cancellation is not allowed, Rev::Api::BadRequestError is raised.
78 79 80 81 82 |
# File 'lib/rev-api/api.rb', line 78 def cancel_order(number) data = { :order_num => number } response = @client.post("/orders/#{number}/cancel", data) Api.verify_post_response(response) end |
#create_input_from_link(url, filename = nil, content_type = nil) ⇒ String
Request creation of a source input based on an external URL which the server will attempt to download.
234 235 236 237 238 239 240 241 242 243 |
# File 'lib/rev-api/api.rb', line 234 def create_input_from_link(url, filename = nil, content_type = nil) request = { :url => url } request[:filename] = filename unless filename.nil? request[:content_type] = content_type unless content_type.nil? response = @client.post("/inputs", request.to_json, { 'Content-Type' => 'application/json' }) Api.verify_post_response(response) response.headers['Location'] end |
#get_all_orders ⇒ Array of Order
Loads all orders for current client. Works by calling get_orders_page multiple times. Use with caution if your order list might be large.
50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/rev-api/api.rb', line 50 def get_all_orders orders = [] page = 0 loop do orders_page = self.get_orders_page page page += 1 orders.push *orders_page.orders break if (page * orders_page.results_per_page >= orders_page.total_count) end orders end |
#get_attachment_content(id, mime_type = nil) {|resp| ... } ⇒ Net::HTTP::Response
Get the raw data for the attachment with given id. Download the contents of an attachment. Use this method to download either a finished transcript, finished translation or a source file for an order. For transcript and translation attachments, you may request to get the contents in a specific representation, specified via a mime-type.
See Order::Attachment::REPRESENTATIONS hash, which contains symbols for currently supported mime types. The authoritative list is in the API documentation at www.rev.com/api/attachmentsgetcontent
If a block is given, the response is passed to the block directly, to allow progressive reading of the data. In this case, the block must itself check for error responses, using Api.verify_get_response. If no block is given, the full response is returned. In that case, if the response is an error, an appropriate error is raised.
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
# File 'lib/rev-api/api.rb', line 115 def (id, mime_type = nil, &block) headers = {} unless mime_type.nil? headers['Accept'] = mime_type headers['Accept-Charset'] = 'utf-8' if mime_type.start_with? 'text/' end if block_given? @client.get_binary("/attachments/#{id}/content", headers, &block) else response = @client.get_binary("/attachments/#{id}/content", headers) Api.verify_get_response(response) response end end |
#get_attachment_content_as_string(id) ⇒ String
Get the content of the attachment with given id as a string. Use this method to grab the contents of a finished transcript or translation as a string. This method should generally not be used for source attachments, as those are typically binary files like MP3s, which cannot be converted to a string.
May raise Rev::Api::NotAcceptableError if the attachment cannot be converted into a text representation.
175 176 177 178 |
# File 'lib/rev-api/api.rb', line 175 def (id) response = self.(id, Attachment::REPRESENTATIONS[:txt]) response.body end |
#get_attachment_metadata(id) ⇒ Attachment
Get metadata about an order attachment. Use this method to retrieve information about an order attachment (either transcript, translation, or source file).
91 92 93 94 95 |
# File 'lib/rev-api/api.rb', line 91 def (id) response = @client.get("/attachments/#{id}") Api.verify_get_response(response) Attachment.new(Api.parse(response)) end |
#get_order(number) ⇒ Order
Returns Order given an order number.
67 68 69 70 71 |
# File 'lib/rev-api/api.rb', line 67 def get_order(number) response = @client.get("/orders/#{number}") Api.verify_get_response(response) Order.new(Api.parse(response)) end |
#get_orders_page(page = 0) ⇒ OrdersListPage
Loads single page of existing orders for current client
39 40 41 42 43 |
# File 'lib/rev-api/api.rb', line 39 def get_orders_page(page = 0) response = @client.get("/orders?page=#{page.to_i}") Api.verify_get_response(response) OrdersListPage.new(Api.parse(response)) end |
#save_attachment_content(id, path, mime_type = nil) ⇒ String
Get the raw data for the attachment with given id. Download the contents of an attachment and save it into a file. Use this method to download either a finished transcript, finished translation or a source file for an order. For transcript and translation attachments, you may request to get the contents in a specific representation, specified via a mime-type.
See Order::Attachment::REPRESENTATIONS hash, which contains symbols for currently supported mime types. The authoritative list is in the API documentation at www.rev.com/api/attachmentsgetcontent
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/rev-api/api.rb', line 145 def (id, path, mime_type = nil) headers = {} unless mime_type.nil? headers['Accept'] = mime_type headers['Accept-Charset'] = 'utf-8' if mime_type.start_with? 'text/' end # same simple approach as box-api does for now: return response.body as-is if path for saving is nil File.open(path, 'wb') do |file| response = @client.get_binary("/attachments/#{id}/content", headers) do |resp| resp.read_body do |segment| file.write(segment) end end Api.verify_get_response(response) end # we don't handle IO-related exceptions path end |
#submit_order(order_request) ⇒ String
www.rev.com/api/ordersposttranscription - for full information
Submit a new order using OrderRequest.
188 189 190 191 192 193 194 |
# File 'lib/rev-api/api.rb', line 188 def submit_order(order_request) response = @client.post("/orders", order_request.to_json, { 'Content-Type' => 'application/json' }) Api.verify_post_response(response) new_order_uri = response.headers['Location'] return new_order_uri.split('/')[-1] end |
#upload_input(path, content_type) ⇒ String
Upload given local file directly as source input for order.
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
# File 'lib/rev-api/api.rb', line 205 def upload_input(path, content_type) filename = Pathname.new(path).basename headers = { 'Content-Disposition' => "attachment; filename=#{filename}", 'Content-Type' => content_type } File.open(path) do |data| response = @client.post_binary("/inputs", data, headers) Api.verify_post_response(response) headers = HTTParty::Response::Headers.new(response.to_hash) return headers['Location'] end end |