예제 #1
0
    def delete(self, commit=False, force=False, debug=False):
        """Delete folder.
        Folder will only be removed from trash if commit is True. This is the case for folders in or out of the trash, so folders
        that are in the trash already will treat delete(commit=False) calls as a no-op.

        REST Documentation: https://www.bitcasa.com/cloudfs-api-docs/api/Delete%20Folder.html

        :param commit:  If true, will permanently remove file instead of moving it to trash. Defaults to False.
        :param force:   If true, will delete folder even if it contains items. Defaults to False.
        :param debug:   If true, will print the the request and response to stdout.

        :returns:   Dictionary with keys for success and the deleted folders last version.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        if self.in_share():
            raise operation_not_allowed("delete folder in share")
        set_debug(self, debug)
        if self.in_trash:
            if commit:
                return self.rest_interface.delete_trash_item(self.path())
            else:
                # nop
                # we're already in the trash, does not make sense to make a delete call if commit is not true.
                return {}
        else:
            folder_to_delete = self.path()
            result = self.rest_interface.delete_folder(folder_to_delete, commit, force)
            if result['success'] and commit == False:
                self.in_trash = True
            return result
예제 #2
0
 def is_linked(self, debug=False):
     """ Can this session make requests?
     :param debug:   If true, will print the the request and response to stdout.
     :return:        True if this session is currently authenticated, false otherwise.
     """
     set_debug(self, debug)
     return self.rest_interface.is_linked()
예제 #3
0
    def delete(self, commit=False, force=False, debug=False):
        """Delete folder.

        Folder will only be removed from trash if commit is True. This is the case for folders in or out of the trash, so folders
        that are in the trash already will treat delete(commit=False) calls as a no-op.


        :param commit:  If true, will permanently remove file instead of moving it to trash. Defaults to False.
        :param force:   If true, will delete folder even if it contains items. Defaults to False.
        :param debug:   If true, will print the the request and response to stdout.

        :returns:   Success and the deleted folders last version.
        :rtype:     Dictionary
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        self._state.check_operation_allowed("delete")
        set_debug(self, debug)
        if self.in_trash:
            if commit:
                result = self.rest_interface.delete_trash_item(self.path)
                self._state.delete(commit, force, result)
                return result
            else:
                # nop
                # we're already in the trash, does not make sense to make a delete call if commit is not true.
                return {}
        else:
            result =  self.rest_interface.delete_folder(self.path, commit, force)
            self._state.delete(commit, force, result)
            return result
예제 #4
0
    def delete(self, commit=False, debug=False, force=False):
        """Delete the file.

        REST Documentation: https://www.bitcasa.com/cloudfs-api-docs/api/Delete%20File.html

        :param commit:  If true, will permanently remove the file. Will move to trash otherwise. Defaults to False.
        :param debug:   If true, will print the the request and response to stdout.

        :returns:   Dictionary with keys for success and the deleted files last version.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        if self.in_trash:
            if commit:
                set_debug(self, debug)
                return self.rest_interface.delete_trash_item(self.path())
            else:
                # nop
                # we're already in the trash, does not make sense to make a delete call if commit is not true.
                return {}

        self._prevent_unsupported_operation('delete')

        set_debug(self, debug)
        result = self.rest_interface.delete_file(self.path(), commit)
        if result['success'] and commit == False:
            self.in_trash = True
        return result
예제 #5
0
    def read(self, size=None, debug=False):
        """File-like interface to read file. Reads size bytes from last offset.

        Reads file synchronously - does not start threads.
        Warning: Each read() call generates on request to CloudFS.


        :param size:    Number of bytes to read. If None, will read entire file. Defaults to None.
        :param debug:   If true, will print the the request and response to stdout.
        :return:        File contents.
        :rtype:         String
        """
        self._state.check_operation_allowed("read")
        set_debug(self, debug)
        range = None
        fp = StringIO.StringIO()
        if size:
            range = [self.tell(), self.tell() + size - 1]
            self.offset += size
        if self.in_share:
            fp.write(self.rest_interface.download_share(self._state.share_key, self.path))
            fp.seek(0)
        else:
            self.rest_interface.download(self.path, self._get_download_callback(fp, False), range=range)

        return fp.read()
예제 #6
0
    def restore(self,
                items,
                method=RestoreValue.fail,
                method_argument=None,
                debug=False):
        """Restore item(s) from trash.
        REST documentation: https://www.bitcasa.com/cloudfs-api-docs/api/Recover%20Trash%20Item.html

        :param items:           Items or paths to restore.
        :param restore_method:  Determines method used to restore item.
        :param method_argument: Expected contents determined by value of restore_method
        :param debug:       If true, will print the the request and response to stdout.
        :return:    Items at new location.
        """
        set_debug(self, debug)
        results = []
        for item in items:
            path = item
            if isinstance(item, Item):
                path = item.path()
            results.append(
                self.rest_interface.restore_trash_item(path, method,
                                                       method_argument))

        return results
예제 #7
0
    def get_item(self, item, debug=False):
        """Returns an Item object representing a given path.

        This is the only endpoint that supports string paths.

        :Note: This does not support shares, use the retrieve_share function instead.

        :param item:    CFS path as a path or string.
        :param debug:   If true, will print the the request and response to stdout.

        :returns:       Representation the Item at the given path.
        :rtype:         Item object.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        path = item
        set_debug(self, debug)

        if type(item) is not str:
            path = str(item)

        parent_path = None
        if path.count('/') > 1: # more than root
            parent_path = path.rstrip('/')
            parent_path = parent_path[0:parent_path.rfind('/')]

        meta = self.rest_interface.generic_get_meta(path)
        items = create_items_from_json(self.rest_interface, meta, parent_path, allow_root=True)[0]
        return items
예제 #8
0
 def is_linked(self, debug=False):
     """ Can this session make requests?
     :param debug:   If true, will print the the request and response to stdout.
     :return:        True if this session is currently authenticated, false otherwise.
     """
     set_debug(self, debug)
     return self.rest_interface.is_linked()
예제 #9
0
    def upload(self, filesystem_path, name=None, mime=None, exists=ExistValues.fail, file_content=None, debug=False):
        """Upload a file to CloudFS.

        :Note: File content can be read from a file or passed into the file_content parameter.

        :param filesystem_path: Source of file data.
        :param name:            Name of file in CloudFS. If left blank, will use name of file in path.
        :param mime:            Mine for new file. If left blank, mime will be detected.
        :param exists:          Behavior if the given name exists on CloudFS. Defaults to fail.
        :param data_inline:     Flag to indicate if the source is a string or a filename.
        :param debug:           If true, will print the the request and response to stdout.

        :returns:               Uploaded file.
        :rtype:                 File object.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        self._state.check_operation_allowed("upload")
        set_debug(self, debug)
        if not name:
            name = os.path.basename(filesystem_path)

        if file_content == None:
            # pass in a handle
            file_content = open(filesystem_path, 'rb')

        files = {'file':[name, file_content]}

        if mime:
            files['file'].append(mime)

        upload_response = self.rest_interface.upload(self.path, files, exists)
        return create_items_from_json(self.rest_interface, upload_response, self.path, self._state)[0]
예제 #10
0
    def delete(self, commit=False, debug=False, force=False):
        """Delete the file.

        :param commit:  If true, will permanently remove the file. Will move to trash otherwise. Defaults to False.
        :param debug:   If true, will print the the request and response to stdout.

        :returns:   Success and the deleted files last version.
        :rtype:     Dictionary.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        self._state.check_operation_allowed("delete")
        if self.in_trash:
            if commit:
                set_debug(self, debug)
                result = self.rest_interface.delete_trash_item(self.path)
                self._state.delete(commit, force, result)
                return result
            else:
                # nop
                # we're already in the trash, does not make sense to make a delete call if commit is not true.
                return {}

        set_debug(self, debug)
        result = self.rest_interface.delete_file(self.path, commit)
        self._state.delete(commit, force, result)
        return result
예제 #11
0
    def save(self, if_conflict=VersionConflictValue.fail, debug=False):
        """Save changes to folder metadata.
        See notes on individual setters for quirks.

        REST Documentation: https://www.bitcasa.com/cloudfs-api-docs/api/Alter%20Folder%20Meta.html

        :param if_conflict: Behavior if the local folder information is out of date.
        :param debug:       If true, will print the the request and response to stdout.

        :returns:   Updated folder object.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        if self.in_share():
            raise operation_not_allowed("save changes to folder in share")
        set_debug(self, debug)
        changes = {'version':self.data['version']}
        for changed_key in self.changed_meta:
            changes[changed_key] = self.data[changed_key]

        self.changed_meta.clear()

        response = self.rest_interface.folder_alter_meta(self.path(), changes, if_conflict)
        self._initialize_self(response)
        return self
예제 #12
0
    def upload(self, source, custom_name=None, custom_mime=None, exists=ExistValues.fail, data_inline=False, debug=False):
        """Upload a file or a string to CloudFS.

        REST Documentation: https://www.bitcasa.com/cloudfs-api-docs/api/Upload%20File.html

        :param source:          Source of file data. String or path to a file.
        :param custom_name:     Name of file in CloudFS. If left blank, will use name of file in path.
        :param custom_mime:     Mine for new file. If left blank, mime will be detected.
        :param exists:          Behavior if the given name exists on CloudFS. Defaults to fail.
        :param data_inline:     Flag to indicate if the source is a string or a filename.
        :param debug:           If true, will print the the request and response to stdout.

        :returns:   New file object.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        if self.in_share():
            raise operation_not_allowed("upload to folder in share")
        set_debug(self, debug)
        if not custom_name:
            custom_name = os.path.basename(source)

        file_data = source
        if not data_inline:
            file_data = open(file_data, 'rb')

        files = {'file':[custom_name, file_data]}

        if custom_mime:
            files['file'].append(custom_mime)

        upload_response = self.rest_interface.upload(self.path(), files, exists)
        return create_items_from_json(self.rest_interface, upload_response, self.path(), self.in_trash)[0]
예제 #13
0
 def list(self, debug=False):
     """List the contents of the share
     :param debug:   If true, will print the the request and response to stdout.
     :return:        List of items in share.
     """
     set_debug(self, debug)
     results = self.rest_interface.browse_share(self.share_key)
     return create_items_from_json(self.rest_interface, results, None, share_key=self.share_key)
예제 #14
0
    def list_trash(self, debug=False):
        """List the items in the trash.

        :param debug:   If true, will print the the request and response to stdout.
        :return:
        """
        set_debug(self, debug)
        result = self.rest_interface.list_trash(self.root_container().path())
        return create_items_from_json(self.rest_interface, result, None, True)
예제 #15
0
    def get_account(self, debug=False):
        """Get an object describing the current users account.
        :param debug:   If true, will print the the request and response to stdout.
        :return:        Account object representing the current user account.
        """
        set_debug(self, debug)

        return Account(self.rest_interface.get_copy(),
                       self.rest_interface.user_profile())
예제 #16
0
    def get_account(self, debug=False):
        """Get an object describing the current users account.
        :param debug:   If true, will print the the request and response to stdout.
        :return:        Account object representing the current user account.
        """
        set_debug(self, debug)

        return Account(self.rest_interface.get_copy(),
                       self.rest_interface.user_profile())
예제 #17
0
    def _save(self, password=None, debug=False):
        set_debug(self, debug)
        if 'share_name' in self.changed_meta:
            # don't do anything if we don't have a new name - nothing else to change
            response = self.rest_interface.alter_share_info(self.share_key, password, new_name=self.name)
            self._initialize_self(response)

        self.changed_meta.clear()
        return self
예제 #18
0
 def authenticate(self, username, password, debug=True):
     """ Attempt to log into the given users' filesystem.
     :param username:    Username of the user.
     :param password:    Password of the user.
     :param debug:       If true, will print the the request and response to stdout.
     :return:            True if successful, False otherwise.
     """
     set_debug(self, debug)
     return self.rest_interface.authenticate(username, password)
예제 #19
0
    def list_trash(self, debug=False):
        """List the items in the trash.

        :param debug:   If true, will print the the request and response to stdout.
        :return:
        """
        set_debug(self, debug)
        result = self.rest_interface.list_trash(self.root_container().path())
        return create_items_from_json(self.rest_interface, result, None, True)
예제 #20
0
 def authenticate(self, username, password, debug=True):
     """ Attempt to log into the given users' filesystem.
     :param username:    Username of the user.
     :param password:    Password of the user.
     :param debug:       If true, will print the the request and response to stdout.
     :return:            True if successful, False otherwise.
     """
     set_debug(self, debug)
     return self.rest_interface.authenticate(username, password)
예제 #21
0
    def create_share(self, items, debug=False):
        set_debug(self, debug)

        if not hasattr(items, '__iter__'):
            items = [items]

        items = map(lambda path: path.path() if isinstance(path, Item) else path, items)

        result = self.rest_interface.create_share(items)
        return create_items_from_json(self.rest_interface, result, None)[0]
예제 #22
0
    def list_trash(self, debug=False):
        """List the items in the trash.

        :param debug:   If true, will print the the request and response to stdout.
        :return:        Items in trash.
        :rtype:         List of Items.
        """
        set_debug(self, debug)
        result = self.rest_interface.list_trash(self.root().path)
        return create_items_from_json(self.rest_interface, result, None, ItemState.TrashState())
예제 #23
0
    def list_shares(self, debug=False):
        """Get all share objects this user has created and not deleted.

        :param debug:   If true, will print the the request and response to stdout.
        :return:        Shares made by current user.
        :rtype:         List of Share objects.
        """
        set_debug(self, debug)
        result = self.rest_interface.list_shares()
        return create_items_from_json(self.rest_interface, result, None)
예제 #24
0
    def user(self, debug=False):
        """Get an object describing the current user.

        :param debug:   If true, will print the the request and response to stdout.
        :return:        The current user.
        :rtype:          User object
        """
        set_debug(self, debug)

        user = self.rest_interface.user_profile()
        return User(self.rest_interface.get_copy(), user)
예제 #25
0
 def list(self, debug=False):
     """List the contents of the share
     :param debug:   If true, will print the the request and response to stdout.
     :return:        List of items in share.
     """
     set_debug(self, debug)
     results = self.rest_interface.browse_share(self.share_key)
     return create_items_from_json(self.rest_interface,
                                   results,
                                   None,
                                   share_key=self.share_key)
예제 #26
0
    def create_share(self, items, debug=False):
        set_debug(self, debug)

        if not hasattr(items, '__iter__'):
            items = [items]

        items = map(
            lambda path: path.path()
            if isinstance(path, Item) else path, items)

        result = self.rest_interface.create_share(items)
        return create_items_from_json(self.rest_interface, result, None)[0]
예제 #27
0
    def _save(self, if_conflict=VersionConflictValue.fail, debug=False):
        set_debug(self, debug)
        changes = {'version':self.data['version']}
        for changed_key in self.changed_meta:
            changes[changed_key] = self.data[changed_key]

        if self.application_data_key in changes:
            changes[self.application_data_key] = json.dumps(changes[self.application_data_key])

        self.changed_meta.clear()
        response = self.rest_interface.folder_alter_meta(self.path, changes, if_conflict)
        self._initialize_self(response)
        return self
예제 #28
0
    def get_history(self, start=-10, stop=None, debug=False):
        """List previous actions taken by the current user.

        See CloudFSRESTAdapter documentation for notes on using this.

        :param start:       First version number to list. If negative, will be treated as a limit on number of actions. Optional, defaults to -10.
        :param stop:        Version number to stop listing at. Not the count of actions. Optional, defaults to none.
        :return:            List of dictionaries which describe actions on the filesystem.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        set_debug(self, debug)

        return self.rest_interface.action_history(start, stop)
예제 #29
0
    def list(self, debug=False):
        """List the contents of this container.

        REST Documentation: https://www.bitcasa.com/cloudfs-api-docs/api/List%20Folder.html

        :param debug: If true, will print the the request and response to stdout.
        :return: Array of Items in container.
        """
        set_debug(self, debug)
        if self.share_key:
            results = self.rest_interface.browse_share(self.share_key, self.path())
            return create_items_from_json(self.rest_interface, results, self.path(), share_key=self.share_key)
        else:
            return list_items_from_path(self.rest_interface, self.path(), self.in_trash)
예제 #30
0
    def restore(self, restore_method=RestoreValue.fail, method_argument=None, debug=False):
        """Restore item from trash.
        REST documentation: https://www.bitcasa.com/cloudfs-api-docs/api/Recover%20Trash%20Item.html
        :param dest:
        :return:
        """
        if self.in_share():
            raise operation_not_allowed("restore item in share")
        if not self.in_trash:
            # TODO: Should we filter on this? It should be reliable - but we can't guarentee it.
            return None

        set_debug(self, debug)
        return self.rest_interface.restore_trash_item(self.path(), restore_method, method_argument)
예제 #31
0
    def get_history(self, start=-10, stop=None, debug=False):
        """List previous actions taken by the current user.

        See CloudFSRESTAdapter documentation for notes on using this.

        :param start:       First version number to list. If negative, will be treated as a limit on number of actions. Optional, defaults to -10.
        :param stop:        Version number to stop listing at. Not the count of actions. Optional, defaults to none.
        :return:            List of dictionaries which describe actions on the filesystem.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        set_debug(self, debug)

        return self.rest_interface.action_history(start, stop)
예제 #32
0
    def set_password(self, password, old_password=None, debug=False):
        """Change password for the share.

        :param password:        New password for share.
        :param old_password:    Current password for share. Optional, but required if a password exists.
        :param debug:           If true, will print the the request and response to stdout.
        :return:                The share.
        :raises SharePasswordError:     If the share requires a password and one is not provided.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        set_debug(self, debug)
        response = self.rest_interface.alter_share_info(self.share_key, old_password, password)
        self._initialize_self(response)
        return self
예제 #33
0
    def download(self, local_path, custom_name=None, synchronous=False, debug=False):
        """Download the file to the local filesystem.
        Does not replicate any metadata.
        If downloads are started with synchronous=True CloudFS SDK will attempt to block until all downloads are complete on destruction. This may block your
        program from exiting. To avoid this, call wait_for_downloads at least once with any arguments (i.e. call with a timeout of 0 to halt downloads immediately)

        REST Documentation: https://www.bitcasa.com/cloudfs-api-docs/api/Download%20File.html

        :param local_path:  Path on local filesystem. Can end with a file name, which will be created or overwritten. Will not create any folders.
        :param custom_name: Can use a separate argument to specify local file name. If file name is included in both local_path and this, local_path takes priority. Optional.
        :param synchronous: If true, download will return immediately and download in separate thread.
        :param debug:       If true, will print the the request and response to stdout.
        :return: None
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        :raises InvalidArgument:        Based on CloudFS Error Code.
        """
        self._prevent_unsupported_operation('download')
        set_debug(self, debug)

        file_name = custom_name
        local_path_except = invalid_argument('local_path', 'Full path of a folder or file that exists. Alternatively, a non-existent file in an existing hierarchy of folders', local_path)

        if exists(local_path):
            if isdir(local_path):
                # use our name / custom name in directory
                folder_path = local_path
            else:
                # use whole users' path
                folder_path, file_name = split(local_path)
                if not file_name:
                    raise local_path_except
        else:
            folders, file = split(local_path)
            if exists(folders):
                file_name = file
                folder_path = folders
            else:
                raise local_path_except

        if not file_name:
            file_name = self.name


        full_path = join(folder_path, file_name)
        fp = open(full_path, 'wb')

        self.rest_interface.download(self.path(), self._get_download_callback(fp, True), background=(not synchronous))
예제 #34
0
    def set_password(self, password, old_password=None, debug=False):
        """Change password for the share.

        :param password:        New password for share.
        :param old_password:    Current password for share. Optional, but required if a password exists.
        :param debug:           If true, will print the the request and response to stdout.
        :return:                The share.
        :raises SharePasswordError:     If the share requires a password and one is not provided.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        set_debug(self, debug)
        response = self.rest_interface.alter_share_info(
            self.share_key, old_password, password)
        self._initialize_self(response)
        return self
예제 #35
0
    def list(self, item, debug=False):
        """List contents of item if the item is a folder.

        :param item:    Folder to list the contents of.
        :param debug:   If true, will print the the request and response to stdout.

        :returns:   Dictionary representation of JSON response.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        path = item
        in_trash = False
        if isinstance(item, Item):
            path = item.url()
            in_trash = item.in_trash
        set_debug(self, debug)
        return list_items_from_path(self.rest_interface, path, in_trash)
예제 #36
0
    def list(self, item, debug=False):
        """List contents of item if the item is a folder.

        :param item:    Folder to list the contents of.
        :param debug:   If true, will print the the request and response to stdout.

        :returns:   Dictionary representation of JSON response.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        path = item
        in_trash = False
        if isinstance(item, Item):
            path = item.url()
            in_trash = item.in_trash
        set_debug(self, debug)
        return list_items_from_path(self.rest_interface, path, in_trash)
예제 #37
0
    def create_share(self, items, password=None, debug=False):
        """Create a new share

        :param items:       Items that should be in the share. These items will be the root of the share unless the list is only one folder. Then the share will contain the folder contents.
        :param password:    Password for share if desired. If omitted, share will be freely accessable with the share key.
        :param debug:       If True, will print the request and response to stdout.
        :return:            Items in share.
        :rtype:             List of Items.
        """
        set_debug(self, debug)

        if not hasattr(items, '__iter__'):
            items = [items]

        items = map(lambda path: path.path if isinstance(path, Item) else path, items)

        result = self.rest_interface.create_share(items)
        return create_items_from_json(self.rest_interface, result, None)[0]
예제 #38
0
    def restore(self, restore_method=RestoreValue.fail, method_argument=None, maintain_validity=False, debug=False):
        """Restore item from trash.

        :param restore_method:      Behavior of restore operation. Optional, defaults to fail.
        :param method_argument:     Argument for restore method. Not used with fail. Path of folder to restore to for rescue. Name of folder to create in root for recreate.
        :param maintain_validity:   Flag indicating if item should keep itself valid. Will require one API request for fail & restore and 2 for recreate.
        :return:                    True if successful, exception otherwise.
        :rtype:                     List of Items
        """
        # TODO: update data after restore
        self._state.check_operation_allowed('restore')
        if not self.in_trash:
            return self

        set_debug(self, debug)
        self.rest_interface.restore_trash_item(self.path, restore_method, method_argument)
        self._state.restore(restore_method, method_argument, maintain_validity)
        return self
예제 #39
0
    def create_folder(self, container_or_name, exists=ExistValues.fail, debug=False):
        """Create a new folder in this folder.

        :param container_or_name:   Container or String name. If arg is a Container, will use that Containers name.
        :param debug:               If true, will print the the request and response to stdout.

        :returns:       New folder.
        :rtype:         Folder object.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        self._state.check_operation_allowed("create_folder")
        set_debug(self, debug)

        if isinstance(container_or_name, Item):
            container_or_name = container_or_name.name

        new_folder_response = self.rest_interface.create_folder(self.path, container_or_name, exists)
        return create_items_from_json(self.rest_interface, new_folder_response, self.path)[0]
예제 #40
0
    def restore(self, items, method=RestoreValue.fail, method_argument=None, debug=False):
        """Restore item(s) from trash.
        REST documentation: https://www.bitcasa.com/cloudfs-api-docs/api/Recover%20Trash%20Item.html

        :param items:           Items or paths to restore.
        :param restore_method:  Determines method used to restore item.
        :param method_argument: Expected contents determined by value of restore_method
        :param debug:       If true, will print the the request and response to stdout.
        :return:    Items at new location.
        """
        set_debug(self, debug)
        results = []
        for item in items:
            path = item
            if isinstance(item, Item):
                path = item.path()
            results.append(self.rest_interface.restore_trash_item(path, method, method_argument))

        return results
예제 #41
0
    def receive(self, location=None, exists=ExistValues.rename, debug=False):
        """Add share contents to the filesystem of this user.

        Behaves differently depending on how the share was crated.
        See Filesystem::create_share for notes on behavior of this command.

        :param location:    Location to copy the share to. Optional, defaults to root.
        :param exists:      How to handle if an item of the same name exists in the destination folder. Defaults to rename.
        :param debug:       If true, will print the the request and response to stdout.
        :return:            List of items created by receiving this share on the users' filesystem.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        set_debug(self, debug)
        if isinstance(location, Item):
            location = location.path()

        result = self.rest_interface.receive_share(self.share_key, location,
                                                   exists)
        return create_items_from_json(self.rest_interface, result, location)
예제 #42
0
    def versions(self, start=0, end=None, limit=10, debug=False):
        """List the previous versions of this file

        The list of files returned are mostly non-functional, though their meta-data is correct. They cannot be read /
        moved / copied, etc.

        :param start:   Lowest version number to list. Optional, defaults to listing all file versions.
        :param stop:    Last version of the file to list. Optional, defaults to listing the most recent version of the file.
        :param limit:   Limit on number of versions returned. Optional, defaults to 10.
        :return:        List of previous versions of this file.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """

        self._prevent_unsupported_operation('versions')
        set_debug(self, debug)
        results = self.rest_interface.list_file_versions(self.path(), start, end, limit)
        if len(results) > 0:
            results = create_items_from_json(self.rest_interface, results, self.path()[:-1], old_versions=True)
        return results
예제 #43
0
    def save(self, password=None, debug=False):
        """Save changes to share.

        Can only change the share's name.

        :param password:    Current password for share. Necassary even if share has been unlocked.
        :param debug:       If true, will print the the request and response to stdout.
        :return:            The modified share.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        set_debug(self, debug)
        if 'share_name' in self.changed_meta:
            # don't do anything if we don't have a new name - nothing else to change
            response = self.rest_interface.alter_share_info(self.share_key,
                                                            password,
                                                            new_name=self.name)
            self._initialize_self(response)

        self.changed_meta.clear()
        return self
예제 #44
0
    def promote(self, debug=False):
        """Promote this version of the file and replace the current version.

        This function will throw an exception if called on a file that is not a previous version.
        Updates this file object to the promoted & current file.

        :return:                        Updated version of file.
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        if not self.old_version:
            raise operation_not_allowed('promote the current version of the file')
        set_debug(self, debug)

        version = self._get('version', None)
        if not version:
            raise ValueError('{} did not have a version field in its data dictionary!:{} \nDid we have a massive & breaking API change?'.format(str(self), self.data))

        response = self.rest_interface.promote_file_version(self.path(), version)
        self._initialize_self(response)
        self.old_version = False
        return self
예제 #45
0
    def read(self, size=None, debug=False):
        """File-like interface to read file. Reads size bytes from last offset.
        Reads file synchronously - does not start threads.
        Warning: Each read() call generates on request to CloudFS.

        REST Documentation: https://www.bitcasa.com/cloudfs-api-docs/api/Download%20File.html

        :param size:    Number of bytes to read. If None, will read entire file. Defaults to None.
        :param debug:   If true, will print the the request and response to stdout.
        :return:    File contents.
        """
        self._prevent_unsupported_operation('read')
        set_debug(self, debug)
        range = None
        fp = StringIO.StringIO()
        if size:
            range = [self.tell(), self.tell() + size - 1]
            self.offset += size

        self.rest_interface.download(self.path(), self._get_download_callback(fp, False), range=range)

        return fp.read()
예제 #46
0
    def save(self, if_conflict=VersionConflictValue.fail, debug=False):
        """Save changes to the file.
        See notes on individual setters for quirks.

        REST Documentation: https://www.bitcasa.com/cloudfs-api-docs/api/Alter%20File%20Meta.html

        :param if_conflict:    Behavior if the file has been updated since retrieving it from Cloudfs.
        :param debug:          If true, will print the the request and response to stdout.

        :returns:  Updated file object
        :raises SessionNotLinked:       CloudFSRESTAdapter is not authenticated.
        :raises AuthenticatedError:     Based on CloudFS Error Code.
        """
        self._prevent_unsupported_operation('save')
        set_debug(self, debug)
        changes = {'version':self.data['version']}
        for changed_key in self.changed_meta:
            changes[changed_key] = self.data[changed_key]

        self.changed_meta.clear()
        response =  self.rest_interface.file_alter_meta(self.path(), changes, if_conflict)
        self._initialize_self(response)
        return self
예제 #47
0
 def _refresh_request(self, debug=False):
     set_debug(self, debug)
     return self.rest_interface.user_profile()
예제 #48
0
 def list_shares(self, debug=False):
     set_debug(self, debug)
     result = self.rest_interface.list_shares()
     return create_items_from_json(self.rest_interface, result, None)
예제 #49
0
 def _refresh_request(self, debug=False):
     set_debug(self, debug)
     return self.rest_interface.browse_share(self.share_key)['share']
예제 #50
0
 def _unlock(self, password, debug=False):
     set_debug(self, debug)
     self.rest_interface.unlock_share(self.share_key, password)
     return self
예제 #51
0
 def _refresh_request(self, debug=False):
     set_debug(self, debug)
     return self.rest_interface.file_get_meta(self.path())