Class: Box::Api

Inherits:
Object
  • Object
show all
Includes:
HTTMultiParty
Defined in:
lib/box/api.rb,
lib/box/api/exceptions.rb

Overview

A wrapper and interface to the Box api. Please visit the Box developers site for a full explaination of what each of the Box api methods expect and perform. TODO: Link to the site.

Defined Under Namespace

Classes: AccountExceeded, EmailInvalid, EmailTaken, ErrorStatus, Exception, Generic, InvalidFolder, InvalidInput, InvalidName, NameTaken, NoAccess, NoParent, NotAuthorized, NotShared, Restricted, SizeExceeded, Unknown, UnknownResponse, UploadFailed

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, url = 'https://box.net', upload_url = 'https://upload.box.net', version = '1.0') ⇒ Api

Note:

Chances are that if the Box api is updated or moves location, this class will no longer work. However, the option to change the defaults still remains.

Create a new API object using the given parameters.

Parameters:

  • api_key (String, Api)

    The api key for your application. You can request one on the Box developer website at http://www.box.net/developers/services. If an Box::Api instance is passed instead, its key is used.

  • url (String) (defaults to: 'https://box.net')

    the url of the Box api.

  • upload_url (String) (defaults to: 'https://upload.box.net')

    the url of the upload host for the Box api.

  • version (String) (defaults to: '1.0')

    the version of the Box api in use.



36
37
38
39
40
41
# File 'lib/box/api.rb', line 36

def initialize(key, url = 'https://box.net', upload_url = 'https://upload.box.net', version = '1.0')
  @default_params = { :api_key => key } # add the api_key to every query

  @base_url = "#{ url }/api/#{ version }" # set the base of the request url
  @upload_url = "#{ upload_url }/api/#{ version }" # uploads use a different url than everything else
end

Instance Attribute Details

#base_urlString

Returns The base url of the box api.

Returns:

  • (String)

    The base url of the box api.



16
17
18
# File 'lib/box/api.rb', line 16

def base_url
  @base_url
end

#upload_urlString

Returns The upload url of the box api.

Returns:

  • (String)

    The upload url of the box api.



19
20
21
# File 'lib/box/api.rb', line 19

def upload_url
  @upload_url
end

Class Method Details

.get_exception(status) ⇒ Exception

Given a status, returning a cooresponding Exception class.

Parameters:

  • status (String)

    The failing status to look for.

Returns:



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/box/api/exceptions.rb', line 39

def self.get_exception(status)
  case status
  # Common responses
  when "application_restricted"
    Restricted
  when "wrong_input", "Wrong input params"
    InvalidInput
  when "not_logged_in", "wrong auth token"
    NotAuthorized
  when "e_no_access", "e_access_denied", "access_denied"
    NoAccess
  # Registration specific responses
  when "email_invalid"
    EmailInvalid
  when "email_already_registered"
    EmailTaken
  when "get_auth_token_error", "e_register"
    Generic
  # Folder/File specific responses
  when "wrong_node"
    InvalidItem
  when "e_folder_id"
    InvalidFolder
  when "no_parent"
    NoParent
  when "invalid_folder_name", "e_no_folder_name", "folder_name_too_big", "upload_invalid_file_name"
    InvalidName
  when "e_input_params"
    InvalidInput
  when "e_filename_in_use", "s_folder_exists"
    NameTaken
  when "e_move_node", "e_copy_node", "e_rename_node", "e_set_description"
    Generic
  # Upload/Download specific responses
  when "upload_some_files_failed"
    UploadFailed
  when "not_enough_free_space"
    AccountExceeded
  when "filesize_limit_exceeded"
    SizeExceeded
  # Comment specific responses
  when "get_comments_error", "add_comment_error", "delete_comment_error"
    Generic
  # Sharing specific responses
  when "file_not_shared"
    NotShared
  when "wrong input params"
    InvalidInput
  when "share_error", "unshare_error", "private_share_error"
    Generic
  else
    Unknown
  end
end

Instance Method Details

#add_comment(target, target_id, message) ⇒ Object

Adds a new comment to the given item.

Parameters:

  • target ("file")

    The type of item.

  • target_id (String)

    The id of the item to add to.

  • message (String)

    The message to use.



315
316
317
# File 'lib/box/api.rb', line 315

def add_comment(target, target_id, message)
  query_rest('add_comment_ok', :action => :add_comment, :target => target, :target_id => target_id, :message => message)
end

#copy(target, target_id, destination_id) ⇒ Object

Note:

The api currently only supports copying files.

Copy the the item to a new destination.

Parameters:

  • target ("file")

    The type of item.

  • target_id (String)

    The id of the item to copy.

  • destination_id (String)

    The id of the parent to copy to.



222
223
224
# File 'lib/box/api.rb', line 222

def copy(target, target_id, destination_id)
  query_rest('s_copy_node', :action => :copy, :target => target, :target_id => target_id, :destination_id => destination_id)
end

#create_folder(parent_id, name, share = 0) ⇒ Object

Create a new folder.

Parameters:

  • parent_id (String)

    The id of the parent folder to use.

  • name (String)

    The name of the newly created folder.

  • shared (Integer)

    The shared state of the new folder.



202
203
204
# File 'lib/box/api.rb', line 202

def create_folder(parent_id, name, share = 0)
  query_rest('create_ok', :action => :create_folder, :parent_id => parent_id, :name => name, :share => share)
end

#delete(target, target_id) ⇒ Object

Delete the item.

Parameters:

  • target ("file", "folder")

    The type of item.

  • target_id (String)

    The id of the item to delete.



239
240
241
# File 'lib/box/api.rb', line 239

def delete(target, target_id)
  query_rest('s_delete_node', :action => :delete, :target => target, :target_id => target_id)
end

#delete_comment(comment_id) ⇒ Object

Deletes a given comment.

Parameters:

  • comment_id (String)

    The id of the comment to delete.



322
323
324
# File 'lib/box/api.rb', line 322

def delete_comment(comment_id)
  query_rest('delete_comment_ok', :action => :delete_comment, :target_id => comment_id)
end

#download(path, file_id, version = nil) ⇒ Object

Note:

You cannot download folders.

Download the file to the given path.

Parameters:

  • path (String)

    The path to write the file to.

  • file_id (String)

    The file id to download.

  • version (Optional, String) (defaults to: nil)

    The version of the file to download.



266
267
268
269
270
# File 'lib/box/api.rb', line 266

def download(path, file_id, version = nil)
  ::File.open(path, 'w') do |file|
    file << query_download([ file_id, version ]) # write the response directly to file
  end
end

#file_embed(id, options = Hash.new) ⇒ Object

Request the HTML embed code for a file.

Parameters:

  • id (String)

    The id of the file to use.

  • options (Hash) (defaults to: Hash.new)

    The properties for the generated preview code. See File#embed_code for a more detailed list of options.



331
332
333
# File 'lib/box/api.rb', line 331

def file_embed(id, options = Hash.new)
  query_rest('s_create_file_embed', { :action => :create_file_embed, :file_id => id }.merge(options))
end

#get_account_infoObject

Get the user’s account info.



180
181
182
# File 'lib/box/api.rb', line 180

def 
  query_rest('get_account_info_ok', :action => :get_account_info)
end

#get_account_tree(folder_id, *args) ⇒ Object

TODO:

Use zip compression to save bandwidth.

Note:

This function can take a long time for large folders.

Get the entire tree of a given folder.

TODO: document the possible arguments.

Parameters:

  • folder_id (String)

    The id of the folder to use.

  • args (Array)

    The arguments to pass along to get_account_tree.



193
194
195
# File 'lib/box/api.rb', line 193

def (folder_id, *args)
  query_rest('listing_ok', :action => :get_account_tree, :folder_id => folder_id, :params => [ 'nozip' ] + args)
end

#get_auth_token(ticket) ⇒ Object

Request an auth token given a ticket.

Parameters:

  • ticket (String)

    the ticket to use.



147
148
149
# File 'lib/box/api.rb', line 147

def get_auth_token(ticket)
  query_rest('get_auth_token_ok', :action => :get_auth_token, :ticket => ticket)
end

#get_comments(target, target_id) ⇒ Object

Gets the comments posted on the given item.

Parameters:

  • target ("file")

    The type of item.

  • target_id (String)

    The id of the item to get.



306
307
308
# File 'lib/box/api.rb', line 306

def get_comments(target, target_id)
  query_rest('get_comments_ok', :action => :get_comments, :target => target, :target_id => target_id)
end

#get_file_info(file_id) ⇒ Object

Get the file info.

Parameters:

  • file_id (String)

    The file id to get info for.



246
247
248
# File 'lib/box/api.rb', line 246

def get_file_info(file_id)
  query_rest('s_get_file_info', :action => :get_file_info, :file_id => file_id)
end

#get_ticketObject

Request a ticket for authorization



140
141
142
# File 'lib/box/api.rb', line 140

def get_ticket
  query_rest('get_ticket_ok', :action => :get_ticket)
end

#handle_response(response, expected = nil) ⇒ Hash

Handle the response of the request.

Parameters:

  • response (Hash)

    The parsed representation of the XML response.

  • expected (String) (defaults to: nil)

    the normal status expected to be returned. If the actual status does not match, an exception is thrown.

Returns:

  • (Hash)

    The response if no errors were found.

Raises:



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/box/api.rb', line 118

def handle_response(response, expected = nil)
  if expected
    begin
      status = response['response']['status']
    rescue
      raise UnknownResponse, "Unknown response: #{ response }"
    end

    unless status == expected # expected is the normal, successful status for this request
      exception = self.class.get_exception(status)
      raise exception, status
    end
  end

  raise ErrorStatus, "HTTP code #{ response.code }" unless response.success? # when the http return code is not normal
  response
end

#logoutObject

Request the user be logged out.



160
161
162
# File 'lib/box/api.rb', line 160

def logout
  query_rest('logout_ok', :action => :logout)
end

#move(target, target_id, destination_id) ⇒ Object

Move the item to a new destination.

Parameters:

  • target ("file", "folder")

    The type of item.

  • target_id (String)

    The id of the item to move.

  • destination_id (String)

    The id of the parent to move to.



211
212
213
# File 'lib/box/api.rb', line 211

def move(target, target_id, destination_id)
  query_rest('s_move_node', :action => :move, :target => target, :target_id => target_id, :destination_id => destination_id)
end

#new_copy(path, file_id, name = nil) ⇒ Object

Upload a new copy of the given file.

TODO: Verfiy this does what I think it does

Parameters:

  • path (String)

    (see #upload)

  • file_id (String)

    The id of the file to copy.

  • name (Optional, String) (defaults to: nil)

    Use a new name as well.



298
299
300
# File 'lib/box/api.rb', line 298

def new_copy(path, file_id, name = nil)
  query_upload('new_copy', file_id, 'upload_ok', :file => ::File.new(path), :new_file_name => name)
end

#overwrite(path, file_id, name = nil) ⇒ Object

Overwrite the given file with a new one.

Parameters:

  • path (String, File or UploadIO)

    (see #upload)

  • file_id (String)

    Replace the file with this id.

  • name (Optional, String) (defaults to: nil)

    Use a new name as well.



287
288
289
290
# File 'lib/box/api.rb', line 287

def overwrite(path, file_id, name = nil)
  path = ::File.new(path) unless path.is_a?(::UploadIO) or path.is_a?(::File)
  query_upload('overwrite', file_id, 'upload_ok', :file => path, :file_name => name)
end

#query_download(args, options = {}) ⇒ Object

Make a download request.

Parameters:

  • query (String)

    the operation to be performed (“download”).

  • args (Array)

    an array of arguments to put in the url.

  • options (Hash) (defaults to: {})

    (see #query_rest)

Returns:

  • The raw binary data of the file.



65
66
67
68
69
# File 'lib/box/api.rb', line 65

def query_download(args, options = {})
  # produces: /download/<auth_token>/<arg1>/<arg2>/<etc>
  url = [ "#{ @base_url }/download", @auth_token, args ].flatten.compact.join('/')
  query_raw('get', url, nil, options)
end

#query_raw(method, url, expected, options = {}) ⇒ Hash

Make a raw request.

@note: HTTParty will automatically parse the response from its native

XML to a nested hash/array structure.

Parameters:

  • method ('get', 'post')

    The HTTP method to use.

  • url (String)

    The url to make the request.

  • expected (String)

    (see #query_rest)

  • options (Hash) (defaults to: {})

    (see #query_rest)

Returns:

  • (Hash)

    A parsed version of the XML response.



98
99
100
101
102
103
104
105
106
107
# File 'lib/box/api.rb', line 98

def query_raw(method, url, expected, options = {})
  response = case method
  when 'get'
    self.class.get(url, :query => @default_params.merge(options))
  when 'post'
    self.class.post(url, :query => @default_params.merge(options), :format => :xml) # known bug with api that only occurs with uploads, will be fixed soon
  end

  handle_response(response, expected)
end

#query_rest(expected, options = {}) ⇒ Hash

Make a normal REST request.

Parameters:

  • expected (String)

    the normal status expected to be returned. If the actual status does not match, an exception is thrown.

  • options (Hash) (defaults to: {})

    The parameters that wish to be passed in the request. These should coorespond to the api specifications, and will be passed along with the api key and auth token.

Returns:

  • (Hash)

    A parsed version of the XML response.



53
54
55
# File 'lib/box/api.rb', line 53

def query_rest(expected, options = {})
  query_raw('get', "#{ @base_url }/rest", expected, options)['response']
end

#query_upload(query, args, expected, options = {}) ⇒ Hash

Make an upload request.

Parameters:

  • query (String)

    The operation to be performed.

  • args (Array)

    (see #query_download)

  • expected (String)

    (see #query_rest)

  • options (Hash) (defaults to: {})

    (see #query_rest)

Returns:

  • (Hash)

    A parsed version of the XML response.



80
81
82
83
84
# File 'lib/box/api.rb', line 80

def query_upload(query, args, expected, options = {})
  # produces: /upload/<auth_token>/<arg1>/<arg2>/<etc>
  url = [ "#{ @upload_url }/#{ query }", @auth_token, args ].flatten.compact.join('/')
  query_raw('post', url, expected, options)['response']
end

#register_new_user(email, password) ⇒ Object

Register a new user.

Parameters:

  • email (String)

    The email address to use.

  • password (String)

    The password to use.



168
169
170
# File 'lib/box/api.rb', line 168

def register_new_user(email, password)
  query_rest('successful_register', :action => :register_new_user, :login => email, :password => password)
end

#rename(target, target_id, new_name) ⇒ Object

Rename the item.

Parameters:

  • target ("file", "folder")

    The type of item.

  • target_id (String)

    The id of the item to rename.

  • new_name (String)

    The new name to be used.



231
232
233
# File 'lib/box/api.rb', line 231

def rename(target, target_id, new_name)
  query_rest('s_rename_node', :action => :rename, :target => target, :target_id => target_id, :new_name => new_name)
end

#set_auth_token(auth_token) ⇒ Object

Add the auth token to every request.

Parameters:

  • auth_token (String)

    The auth token to add to every request.



154
155
156
157
# File 'lib/box/api.rb', line 154

def set_auth_token(auth_token)
  @auth_token = auth_token
  @default_params[:auth_token] = auth_token
end

#set_description(target, target_id, description) ⇒ Object

Set the item description.

Parameters:

  • target ("file", "folder")

    The type of item.

  • target_id (String)

    The id of the item to describe.

  • description (String)

    The description to use.



255
256
257
# File 'lib/box/api.rb', line 255

def set_description(target, target_id, description)
  query_rest('s_set_description', :action => :set_description, :target => target, :target_id => target_id, :description => description)
end

#share_private(target, target_id, emails, options = Hash.new) ⇒ Object

Share an item privately, making it accessible only via email.

Parameters:

  • target (String)

    The type of item.

  • target_id (String)

    The id of the item to share.

  • emails (Array)

    The email addresses of the individuals to share with.

  • options (Hash) (defaults to: Hash.new)

    Extra options related to notifications. Please read the developer documentation for more details.



353
354
355
# File 'lib/box/api.rb', line 353

def share_private(target, target_id, emails, options = Hash.new)
  query_rest('private_share_ok', { :action => :private_share, :target => target, :target_id => target_id, :emails => emails }.merge(options))
end

#share_public(target, target_id, options = Hash.new) ⇒ Object

Share an item publically, making it accessible via a share link.

Parameters:

  • target (String)

    The type of item.

  • target_id (String)

    The id of the item to share.

  • options (Hash) (defaults to: Hash.new)

    Extra options related to notifications. Please read the developer documentation for more details.



341
342
343
# File 'lib/box/api.rb', line 341

def share_public(target, target_id, options = Hash.new)
  query_rest('share_ok', { :action => :public_share, :target => target, :target_id => target_id }.merge(options))
end

#unshare_public(target, target_id) ⇒ Object

Stop sharing an item publically.

Parameters:

  • target (String)

    The type of item.

  • target_id (String)

    The id of the item to unshare.



361
362
363
# File 'lib/box/api.rb', line 361

def unshare_public(target, target_id)
  query_rest('unshare_ok', :action => :public_unshare, :target => target, :target_id => target_id)
end

#upload(path, folder_id, new_copy = false) ⇒ Object

Upload the file to the specified folder.

Parameters:

  • path (String, File or UploadIO)

    Upload the file at the given path, or a File or UploadIO object..

  • folder_id (String)

    The folder id of the parent folder to use.

  • new_copy (Optional, Boolean) (defaults to: false)

    Upload a new copy instead of overwriting.



277
278
279
280
# File 'lib/box/api.rb', line 277

def upload(path, folder_id, new_copy = false)
  path = ::File.new(path) unless path.is_a?(::UploadIO) or path.is_a?(::File)
  query_upload('upload', folder_id, 'upload_ok', :file => path, :new_copy => new_copy)
end

#verify_registration_email(email) ⇒ Object

Verify a registration email.

Parameters:

  • email (String)

    The email address to check.



175
176
177
# File 'lib/box/api.rb', line 175

def verify_registration_email(email)
  query_rest('email_ok', :action => :verify_registration_email, :login => email)
end