Last active
August 29, 2015 14:01
-
-
Save lakim/2d1c767bdb8700ef3313 to your computer and use it in GitHub Desktop.
Box View API Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module BoxView | |
class SessionError < StandardError; end | |
class GetError < StandardError; end | |
class RetryError < StandardError | |
attr_reader :retry_after | |
def initialize(retry_after) | |
@retry_after = retry_after | |
end | |
end | |
class Client | |
include HTTParty | |
base_uri 'https://view-api.box.com/1' | |
headers 'Authorization' => "Token #{SETTINGS['box']['api_key']}", | |
'Content-Type' => 'application/json' | |
class << self | |
def create_session(url) | |
response = post('/documents', body: { url: url }.to_json) | |
if response['type'] == 'document' && response['id'].present? | |
document_id = response['id'] | |
else | |
raise SessionError, "No document_id in response: #{response.inspect}" | |
end | |
document_id | |
end | |
def get_pdf_file(document_id) | |
response = get("/documents/#{document_id}/content.pdf") | |
retry_after = response.headers['retry-after'] | |
if response.code == 200 | |
file = Tempfile.new([document_id, '.pdf']) | |
file.binmode | |
file.write(response.parsed_response) | |
file | |
elsif retry_after | |
raise RetryError.new(retry_after.to_i) | |
else | |
raise GetError, "Invalid response: #{response.inspect}" | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment