class DropboxClient

This is the Dropbox Client API you’ll be working with most often. You need to give it a DropboxSession which has already been authorized, or which it can authorize.

Constants

RESERVED_CHARACTERS

From the oauth spec plus “/”. Slash should not be ecsaped

Public Class Methods

new(session, root="app_folder", locale=nil) click to toggle source

Initialize a new DropboxClient. You need to give it a session which has been authorized. See documentation on DropboxSession for how to authorize it.

# File dropbox_sdk.rb, line 298
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

Public Instance Methods

account_info() click to toggle source

Returns account info in a Hash object

For a detailed description of what this call returns, visit: www.dropbox.com/developers/reference/api#account-info

# File dropbox_sdk.rb, line 351
def account_info()
    response = @session.do_get build_url("/account/info")
    parse_response(response)
end
add_copy_ref(to_path, copy_ref) click to toggle source

Adds the file referenced by the copy ref to the specified path

Args:

  • copy_ref: A copy ref string that was returned from a #create_copy_ref call. The copy_ref can be created from any other Dropbox account, or from the same account.

  • to_path: The path to where the file will be created.

Returns:

  • A hash with the metadata of the new file.

# File dropbox_sdk.rb, line 931
def add_copy_ref(to_path, copy_ref)
    path = "/fileops/copy"

    params = {'from_copy_ref' => copy_ref,
              'to_path' => "#{format_path(to_path)}",
              'root' => @root}

    response = @session.do_post(build_url(path, params))

    parse_response(response)
end
commit_chunked_upload(to_path, upload_id, overwrite=false, parent_rev=nil) click to toggle source
# File dropbox_sdk.rb, line 488
def commit_chunked_upload(to_path, upload_id, overwrite=false, parent_rev=nil)  #:nodoc
    params = {'overwrite' => overwrite.to_s,
              'upload_id' => upload_id,
              'parent_rev' => parent_rev.to_s,
            }
    @session.do_post(build_url("/commit_chunked_upload/#{@root}#{format_path(to_path)}", params, content_server=true))
end
create_copy_ref(path) click to toggle source

Creates and returns a copy ref for a specific file. The copy ref can be used to instantly copy that file to the Dropbox of another account.

Args:

  • path: The path to the file for a copy ref to be created on.

Returns:

  • A Hash object that looks like the following example:

    {"expires"=>"Fri, 31 Jan 2042 21:01:05 +0000", "copy_ref"=>"z1X6ATl6aWtzOGq0c3g5Ng"}
    
# File dropbox_sdk.rb, line 914
def create_copy_ref(path)
    path = "/copy_ref/#{@root}#{format_path(path)}"

    response = @session.do_get(build_url(path, {}))

    parse_response(response)
end
delta(cursor=nil) click to toggle source

A way of letting you keep a local representation of the Dropbox folder heirarchy. You can periodically call delta() to get a list of “delta entries”, which are instructions on how to update your local state to match the server’s state.

Arguments:

  • cursor: On the first call, omit this argument (or pass in nil). On subsequent calls, pass in the cursor string returned by the previous call.

Returns: A hash with three fields.

  • entries: A list of “delta entries” (described below)

  • reset: If true, you should reset local state to be an empty folder before processing the list of delta entries. This is only true only in rare situations.

  • cursor: A string that is used to keep track of your current state. On the next call to delta(), pass in this value to return entries that were recorded since the cursor was returned.

  • has_more: If true, then there are more entries available; you can call delta() again immediately to retrieve those entries. If false, then wait at least 5 minutes (preferably longer) before checking again.

Delta Entries: Each entry is a 2-item list of one of following forms:

  • [path, metadata]: Indicates that there is a file/folder at the given path. You should add the entry to your local state. (The metadata value is the same as what would be returned by the metadata() call.)

    • If the path refers to parent folders that don’t yet exist in your local state, create those parent folders in your local state. You will eventually get entries for those parent folders.

    • If the new entry is a file, replace whatever your local state has at path with the new entry.

    • If the new entry is a folder, check what your local state has at path. If it’s a file, replace it with the new entry. If it’s a folder, apply the new metadata to the folder, but do not modify the folder’s children.

  • [path, nil]: Indicates that there is no file/folder at the path on Dropbox. To update your local state to match, delete whatever is at path, including any children (you will sometimes also get separate delta entries for each child, but this is not guaranteed). If your local state doesn’t have anything at path, ignore this entry.

Remember: Dropbox treats file names in a case-insensitive but case-preserving way. To facilitate this, the path strings above are lower-cased versions of the actual path. The metadata dicts have the original, case-preserved path.

# File dropbox_sdk.rb, line 872
def delta(cursor=nil)
    params = {}
    if cursor
        params['cursor'] = cursor
    end

    response = @session.do_post build_url("/delta", params)
    parse_response(response)
end
file_copy(from_path, to_path) click to toggle source

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:

# File dropbox_sdk.rb, line 584
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) click to toggle source

Create a folder.

Arguments:

  • path: The path of the new folder.

Returns:

# File dropbox_sdk.rb, line 603
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) click to toggle source

Deletes a file

Arguments:

  • path: The path of the file to delete

Returns:

# File dropbox_sdk.rb, line 622
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) click to toggle source

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:

# File dropbox_sdk.rb, line 642
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
get_chunked_uploader(file_obj, total_size) click to toggle source

Returns a ChunkedUploader object.

Args:

  • file_obj: The file-like object to be uploaded. Must support .read()

  • total_size: The total size of file_obj

# File dropbox_sdk.rb, line 409
def get_chunked_uploader(file_obj, total_size)
    ChunkedUploader.new(self, file_obj, total_size)
end
get_file(from_path, rev=nil) click to toggle source

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.

# File dropbox_sdk.rb, line 513
def get_file(from_path, rev=nil)
    response = get_file_impl(from_path, rev)
    parse_response(response, raw=true)
end
get_file_and_metadata(from_path, rev=nil) click to toggle source

Download a file and get its metadata.

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.

  • The file metadata as a hash.

# File dropbox_sdk.rb, line 527
def get_file_and_metadata(from_path, rev=nil)
    response = get_file_impl(from_path, rev)
    parsed_response = parse_response(response, raw=true)
    metadata = parse_metadata(response)
    return parsed_response, metadata
end
media(path) click to toggle source

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'}
# File dropbox_sdk.rb, line 772
def media(path)
    response = @session.do_get build_url("/media/#{@root}#{format_path(path)}")
    parse_response(response)
end
metadata(path, file_limit=25000, list=true, hash=nil, rev=nil, include_deleted=false) click to toggle source

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 25,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.

  • rev: Optional. The revision of the file to retrieve the metadata for. This parameter only applies for files. If omitted, you’ll receive the most recent revision metadata.

  • include_deleted: Specifies whether to include deleted files in metadata results.

Returns:

# File dropbox_sdk.rb, line 675
def metadata(path, file_limit=25000, list=true, hash=nil, rev=nil, include_deleted=false)
    params = {
        "file_limit" => file_limit.to_s,
        "list" => list.to_s,
        "include_deleted" => include_deleted.to_s
    }

    params["hash"] = hash if hash
    params["rev"] = rev if rev

    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
partial_chunked_upload(data, upload_id=nil, offset=nil) click to toggle source
# File dropbox_sdk.rb, line 496
def partial_chunked_upload(data, upload_id=nil, offset=nil)  #:nodoc
    params = {}
    params['upload_id'] = upload_id.to_s if upload_id
    params['offset'] = offset.to_s if offset
    @session.do_put(build_url('/chunked_upload', params, content_server=true),
                            {'Content-Type' => "application/octet-stream"},
                            data)
end
put_file(to_path, file_obj, overwrite=false, parent_rev=nil) click to toggle source

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.

# File dropbox_sdk.rb, line 388
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) click to toggle source

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:

# File dropbox_sdk.rb, line 751
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) click to toggle source

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:

# File dropbox_sdk.rb, line 730
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
shares(path) click to toggle source

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/reference/api#shares
# File dropbox_sdk.rb, line 791
def shares(path)
    response = @session.do_get build_url("/shares/#{@root}#{format_path(path)}")
    parse_response(response)
end
thumbnail(from_path, size='large') click to toggle source

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’ (32x32), ‘medium’ (64x64), ‘large’ (128x128), ‘s’ (64x64), ‘m’ (128x128), ‘l’ (640x640), and ‘xl’ (1024x1024) are officially supported sizes. Check www.dropbox.com/developers/reference/api#thumbnails for more details. [defaults to large]

Returns:

  • The thumbnail data

# File dropbox_sdk.rb, line 807
def thumbnail(from_path, size='large')
    response = thumbnail_impl(from_path, size)
    parse_response(response, raw=true)
end
thumbnail_and_metadata(from_path, size='large') click to toggle source

Download a thumbnail for an image along with the image’s metadata.

Arguments:

  • from_path: The path to the file to be thumbnailed.

  • size: A string describing the desired thumbnail size. See thumbnail() for details.

Returns:

  • The thumbnail data

  • The metadata for the image as a hash

# File dropbox_sdk.rb, line 821
def thumbnail_and_metadata(from_path, size='large')
    response = thumbnail_impl(from_path, size)
    parsed_response = parse_response(response, raw=true)
    metadata = parse_metadata(response)
    return parsed_response, metadata
end