Class: DropboxClient
- Inherits:
-
Object
- Object
- DropboxClient
- Defined in:
- lib/dropbox_sdk.rb
Overview
This is the Dropbox Client API you’ll be working with most often. You need to give it a DropboxSession which has already been authorize, or which it can authorize.
Constant Summary collapse
- RESERVED_CHARACTERS =
From the oauth spec plus “/”. Slash should not be ecsaped
/[^a-zA-Z0-9\-\.\_\~\/]/
Instance Method Summary collapse
-
#account_info ⇒ Object
Returns account info in a Hash object.
-
#build_url(url, params = nil, content_server = false) ⇒ Object
:nodoc:.
-
#file_copy(from_path, to_path) ⇒ Object
Copy a file or folder to a new location.
-
#file_create_folder(path) ⇒ Object
Create a folder.
-
#file_delete(path) ⇒ Object
Deletes a file.
-
#file_move(from_path, to_path) ⇒ Object
Moves a file.
-
#format_path(path, escape = true) ⇒ Object
:nodoc:.
-
#get_file(from_path, rev = nil) ⇒ Object
Download a file.
-
#initialize(session, root = "app_folder", locale = nil) ⇒ DropboxClient
constructor
Initialize a new DropboxClient.
-
#media(path) ⇒ Object
Returns a direct link to a media file All of Dropbox’s API methods require OAuth, which may cause problems in situations where an application expects to be able to hit a URL multiple times (for example, a media player seeking around a video file).
-
#metadata(path, file_limit = 10000, list = true, hash = nil) ⇒ Object
Retrives metadata for a file or folder.
-
#parse_response(response, raw = false) ⇒ Object
Parse response.
-
#put_file(to_path, file_obj, overwrite = false, parent_rev = nil) ⇒ Object
Uploads a file to a server.
-
#restore(path, rev) ⇒ Object
Restore a file to a previous revision.
-
#revisions(path, rev_limit = 1000) ⇒ Object
Retrive revisions of a file.
-
#search(path, query, file_limit = 10000, include_deleted = false) ⇒ Object
Search directory for filenames matching query.
-
#shares(path) ⇒ Object
Get a URL to share a media file Shareable links created on Dropbox are time-limited, but don’t require any authentication, so they can be given out freely.
-
#thumbnail(from_path, size = 'large') ⇒ Object
Download a thumbnail for an image.
Constructor Details
#initialize(session, root = "app_folder", locale = nil) ⇒ DropboxClient
Initialize a new DropboxClient. You need to get it a session which either has been authorized. See documentation on DropboxSession for how to authorize it.
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
# File 'lib/dropbox_sdk.rb', line 280 def initialize(session, root="app_folder", locale=nil) session.get_access_token @root = root.to_s # If they passed in a symbol, make it a string if not ["dropbox","app_folder"].include?(@root) raise DropboxError.new("root must be :dropbox or :app_folder") end if @root == "app_folder" #App Folder is the name of the access type, but for historical reasons #sandbox is the URL root component that indicates this @root = "sandbox" end @locale = locale @session = session end |
Instance Method Details
#account_info ⇒ Object
Returns account info in a Hash object
For a detailed description of what this call returns, visit: www.dropbox.com/developers/docs#account-info
334 335 336 337 |
# File 'lib/dropbox_sdk.rb', line 334 def account_info() response = @session.do_get build_url("/account/info") parse_response(response) end |
#build_url(url, params = nil, content_server = false) ⇒ Object
:nodoc:
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 |
# File 'lib/dropbox_sdk.rb', line 651 def build_url(url, params=nil, content_server=false) # :nodoc: port = 443 host = content_server ? Dropbox::API_CONTENT_SERVER : Dropbox::API_SERVER versioned_url = "/#{Dropbox::API_VERSION}#{url}" target = URI::Generic.new("https", nil, host, port, nil, versioned_url, nil, nil, nil) #add a locale param if we have one #initialize a params object is we don't have one if @locale (params ||= {})['locale']=@locale end if params target.query = params.collect {|k,v| URI.escape(k) + "=" + URI.escape(v) }.join("&") end target.to_s end |
#file_copy(from_path, to_path) ⇒ Object
Copy a file or folder to a new location.
Arguments:
-
from_path: The path to the file or folder to be copied.
-
to_path: The destination path of the file or folder to be copied. This parameter should include the destination filename (e.g. from_path: ‘/test.txt’, to_path: ‘/dir/test.txt’). If there’s already a file at the to_path, this copy will be renamed to be unique.
Returns:
-
A hash with the metadata of the new copy of the file or folder. For a detailed description of what this call returns, visit: www.dropbox.com/developers/docs#fileops-copy
419 420 421 422 423 424 425 426 427 |
# File 'lib/dropbox_sdk.rb', line 419 def file_copy(from_path, to_path) params = { "root" => @root, "from_path" => format_path(from_path, false), "to_path" => format_path(to_path, false), } response = @session.do_post build_url("/fileops/copy", params) parse_response(response) end |
#file_create_folder(path) ⇒ Object
Create a folder.
Arguments:
-
path: The path of the new folder.
Returns:
-
A hash with the metadata of the newly created folder. For a detailed description of what this call returns, visit: www.dropbox.com/developers/docs#fileops-create-folder
438 439 440 441 442 443 444 445 446 |
# File 'lib/dropbox_sdk.rb', line 438 def file_create_folder(path) params = { "root" => @root, "path" => format_path(path, false), } response = @session.do_post build_url("/fileops/create_folder", params) parse_response(response) end |
#file_delete(path) ⇒ Object
Deletes a file
Arguments:
-
path: The path of the file to delete
Returns:
-
A Hash with the metadata of file just deleted. For a detailed description of what this call returns, visit: www.dropbox.com/developers/docs#fileops-delete
457 458 459 460 461 462 463 464 |
# File 'lib/dropbox_sdk.rb', line 457 def file_delete(path) params = { "root" => @root, "path" => format_path(path, false), } response = @session.do_post build_url("/fileops/delete", params) parse_response(response) end |
#file_move(from_path, to_path) ⇒ Object
Moves a file
Arguments:
-
from_path: The path of the file to be moved
-
to_path: The destination path of the file or folder to be moved If the file or folder already exists, it will be renamed to be unique.
Returns:
-
A Hash with the metadata of file or folder just moved. For a detailed description of what this call returns, visit: www.dropbox.com/developers/docs#fileops-delete
477 478 479 480 481 482 483 484 485 |
# File 'lib/dropbox_sdk.rb', line 477 def file_move(from_path, to_path) params = { "root" => @root, "from_path" => format_path(from_path, false), "to_path" => format_path(to_path, false), } response = @session.do_post build_url("/fileops/move", params) parse_response(response) end |
#format_path(path, escape = true) ⇒ Object
:nodoc:
676 677 678 679 680 681 682 683 684 685 686 687 688 |
# File 'lib/dropbox_sdk.rb', line 676 def format_path(path, escape=true) # :nodoc: path = path.gsub(/\/+/,"/") # replace multiple slashes with a single one path = path.gsub(/^\/?/,"/") # ensure the path starts with a slash path.gsub(/\/?$/,"") # ensure the path doesn't end with a slash return URI.escape(path, RESERVED_CHARACTERS) if escape path end |
#get_file(from_path, rev = nil) ⇒ Object
Download a file
Args:
-
from_path: The path to the file to be downloaded
-
rev: A previous revision value of the file to be downloaded
Returns:
-
The file contents.
395 396 397 398 399 400 401 402 403 |
# File 'lib/dropbox_sdk.rb', line 395 def get_file(from_path, rev=nil) params = {} params['rev'] = rev.to_s if rev path = "/files/#{@root}#{format_path(from_path)}" response = @session.do_get build_url(path, params, content_server=true) parse_response(response, raw=true) end |
#media(path) ⇒ Object
Returns a direct link to a media file All of Dropbox’s API methods require OAuth, which may cause problems in situations where an application expects to be able to hit a URL multiple times (for example, a media player seeking around a video file). This method creates a time-limited URL that can be accessed without any authentication.
Arguments:
-
path: The file to stream.
Returns:
-
A Hash object that looks like the following:
{'url': 'https://dl.dropbox.com/0/view/wvxv1fw6on24qw7/file.mov', 'expires': 'Thu, 16 Sep 2011 01:01:25 +0000'}
601 602 603 604 |
# File 'lib/dropbox_sdk.rb', line 601 def media(path) response = @session.do_get build_url("/media/#{@root}#{format_path(path)}") parse_response(response) end |
#metadata(path, file_limit = 10000, list = true, hash = nil) ⇒ Object
Retrives metadata for a file or folder
Arguments:
-
path: The path to the file or folder.
-
list: Whether to list all contained files (only applies when path refers to a folder).
-
file_limit: The maximum number of file entries to return within a folder. If the number of files in the directory exceeds this limit, an exception is raised. The server will return at max 10,000 files within a folder.
-
hash: Every directory listing has a hash parameter attached that can then be passed back into this function later to save on bandwidth. Rather than returning an unchanged folder’s contents, if the hash matches a DropboxNotModified exception is raised.
Returns:
-
A Hash object with the metadata of the file or folder (and contained files if appropriate). For a detailed description of what this call returns, visit: www.dropbox.com/developers/docs#metadata
506 507 508 509 510 511 512 513 514 515 516 517 518 519 |
# File 'lib/dropbox_sdk.rb', line 506 def (path, file_limit=10000, list=true, hash=nil) params = { "file_limit" => file_limit.to_s, "list" => list.to_s } params["hash"] = hash if hash response = @session.do_get build_url("/metadata/#{@root}#{format_path(path)}", params=params) if response.kind_of? Net::HTTPRedirection raise DropboxNotModified.new("metadata not modified") end parse_response(response) end |
#parse_response(response, raw = false) ⇒ Object
Parse response. You probably shouldn’t be calling this directly. This takes responses from the server and parses them. It also checks for errors and raises exceptions with the appropriate messages.
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
# File 'lib/dropbox_sdk.rb', line 300 def parse_response(response, raw=false) # :nodoc: if response.kind_of?(Net::HTTPServerError) raise DropboxError.new("Dropbox Server Error: #{response} - #{response.body}", response) elsif response.kind_of?(Net::HTTPUnauthorized) raise DropboxAuthError.new(response, "User is not authenticated.") elsif not response.kind_of?(Net::HTTPSuccess) begin d = JSON.parse(response.body) rescue raise DropboxError.new("Dropbox Server Error: body=#{response.body}", response) end if d['user_error'] and d['error'] raise DropboxError.new(d['error'], response, d['user_error']) #user_error is translated elsif d['error'] raise DropboxError.new(d['error'], response) else raise DropboxError.new(response.body, response) end end return response.body if raw begin return JSON.parse(response.body) rescue JSON::ParserError raise DropboxError.new("Unable to parse JSON response", response) end end |
#put_file(to_path, file_obj, overwrite = false, parent_rev = nil) ⇒ Object
Uploads a file to a server. This uses the HTTP PUT upload method for simplicity
Arguments:
-
to_path: The directory path to upload the file to. If the destination directory does not yet exist, it will be created.
-
file_obj: A file-like object to upload. If you would like, you can pass a string as file_obj.
-
overwrite: Whether to overwrite an existing file at the given path. [default is False] If overwrite is False and a file already exists there, Dropbox will rename the upload to make sure it doesn’t overwrite anything. You must check the returned metadata to know what this new name is. This field should only be True if your intent is to potentially clobber changes to a file that you don’t know about.
-
parent_rev: The rev field from the ‘parent’ of this upload. [optional] If your intent is to update the file at the given path, you should pass the parent_rev parameter set to the rev value from the most recent metadata you have of the existing file at that path. If the server has a more recent version of the file at the specified path, it will automatically rename your uploaded file, spinning off a conflict. Using this parameter effectively causes the overwrite parameter to be ignored. The file will always be overwritten if you send the most-recent parent_rev, and it will never be overwritten you send a less-recent one.
Returns:
-
a Hash containing the metadata of the newly uploaded file. The file may have a different name if it conflicted.
Simple Example
client = DropboxClient(session, :app_folder)
#session is a DropboxSession I've already authorized
client.put_file('/test_file_on_dropbox', open('/tmp/test_file'))
This will upload the “/tmp/test_file” from my computer into the root of my App’s app folder and call it “test_file_on_dropbox”. The file will not overwrite any pre-existing file.
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 |
# File 'lib/dropbox_sdk.rb', line 371 def put_file(to_path, file_obj, overwrite=false, parent_rev=nil) path = "/files_put/#{@root}#{format_path(to_path)}" params = { 'overwrite' => overwrite.to_s } params['parent_rev'] = parent_rev unless parent_rev.nil? response = @session.do_put(build_url(path, params, content_server=true), {"Content-Type" => "application/octet-stream"}, file_obj) parse_response(response) end |
#restore(path, rev) ⇒ Object
Restore a file to a previous revision.
Arguments:
-
path: The file to restore. Note that folders can’t be restored.
-
rev: A previous rev value of the file to be restored to.
Returns:
-
A Hash object with a list the metadata of the file or folders restored For a detailed description of what this call returns, visit: www.dropbox.com/developers/docs#search
580 581 582 583 584 585 586 587 |
# File 'lib/dropbox_sdk.rb', line 580 def restore(path, rev) params = { 'rev' => rev.to_s } response = @session.do_post build_url("/restore/#{@root}#{format_path(path)}", params) parse_response(response) end |
#revisions(path, rev_limit = 1000) ⇒ Object
Retrive revisions of a file
Arguments:
-
path: The file to fetch revisions for. Note that revisions are not available for folders.
-
rev_limit: The maximum number of file entries to return within a folder. The server will return at max 1,000 revisions.
Returns:
-
A Hash object with a list of the metadata of the all the revisions of all matches files (up to rev_limit entries) For a detailed description of what this call returns, visit: www.dropbox.com/developers/docs#revisions
559 560 561 562 563 564 565 566 567 568 |
# File 'lib/dropbox_sdk.rb', line 559 def revisions(path, rev_limit=1000) params = { 'rev_limit' => rev_limit.to_s } response = @session.do_get build_url("/revisions/#{@root}#{format_path(path)}", params) parse_response(response) end |
#search(path, query, file_limit = 10000, include_deleted = false) ⇒ Object
Search directory for filenames matching query
Arguments:
-
path: The directory to search within
-
query: The query to search on (3 character minimum)
-
file_limit: The maximum number of file entries to return/ If the number of files exceeds this limit, an exception is raised. The server will return at max 10,000
-
include_deleted: Whether to include deleted files in search results
Returns:
-
A Hash object with a list the metadata of the file or folders matching query inside path. For a detailed description of what this call returns, visit: www.dropbox.com/developers/docs#search
535 536 537 538 539 540 541 542 543 544 |
# File 'lib/dropbox_sdk.rb', line 535 def search(path, query, file_limit=10000, include_deleted=false) params = { 'query' => query, 'file_limit' => file_limit.to_s, 'include_deleted' => include_deleted.to_s } response = @session.do_get build_url("/search/#{@root}#{format_path(path)}", params) parse_response(response) end |
#shares(path) ⇒ Object
Get a URL to share a media file Shareable links created on Dropbox are time-limited, but don’t require any authentication, so they can be given out freely. The time limit should allow at least a day of shareability, though users have the ability to disable a link from their account if they like.
Arguments:
-
path: The file to share.
Returns:
-
A Hash object that looks like the following example:
{'url': 'http://www.dropbox.com/s/m/a2mbDa2', 'expires': 'Thu, 16 Sep 2011 01:01:25 +0000'}For a detailed description of what this call returns, visit:
https://www.dropbox.com/developers/docs#share
620 621 622 623 |
# File 'lib/dropbox_sdk.rb', line 620 def shares(path) response = @session.do_get build_url("/shares/#{@root}#{format_path(path)}") parse_response(response) end |
#thumbnail(from_path, size = 'large') ⇒ Object
Download a thumbnail for an image.
Arguments:
-
from_path: The path to the file to be thumbnailed.
-
size: A string describing the desired thumbnail size. At this time, ‘small’, ‘medium’, and ‘large’ are officially supported sizes (32x32, 64x64, and 128x128 respectively), though others may be available. Check www.dropbox.com/developers/docs#thumbnails for more details. [defaults to large]
Returns:
-
The thumbnail data
636 637 638 639 640 641 642 643 644 645 646 647 648 649 |
# File 'lib/dropbox_sdk.rb', line 636 def thumbnail(from_path, size='large') from_path = format_path(from_path, false) raise DropboxError.new("size must be small medium or large. (not '#{size})") unless ['small','medium','large'].include?(size) params = { "size" => size } url = build_url("/thumbnails/#{@root}#{from_path}", params, content_server=true) response = @session.do_get url parse_response(response, raw=true) end |